2025年12月19日

あれまぁ~” についての 5 の意見

  1. あー
    関数名を配列に入れて順次コールしたかったと。
    別々のクラスの同じ名前のメンバ関数にして、各クラスのインスタンスを
    基底クラスかインタフェースの配列に入れてポリモーフィズム使えば簡単では?
    Java はよくしらないけどこんな感じ。
    public class MyTest {
    public static void main(String[] args) {
    TestInterface[] testlist = {new IfBlock(), new ElseIfBlockA(), new ElseIfBlockB()};
    for (TestInterface t: testlist) {
    String ResultFor100 = t.Do(100);
    System.out.println(ResultFor100);
    String ResultFor70 = t.Do(70);
    System.out.println(ResultFor70);
    String ResultFor40 = t.Do(40);
    System.out.println(ResultFor40);
    }
    }
    }
    interface TestInterface {
    String Do(int x);
    }
    class IfBlock implements TestInterface {
    public String Do(int x) {
    if (x >= 80) {
    return “A (by IfSingle)”;
    }
    else if (x >= 50) {
    return “B (by IfSingle)”;
    }
    return “C (by IfSingle)”;
    }
    }
    class ElseIfBlockA implements TestInterface {
    public String Do(int x) {
    if (x >= 80) {
    return “A (by ElseIfBlockA)”;
    }
    else {
    if (x >= 50) {
    return “B (by ElseIfBlockA)”;
    }
    else {
    return “C (by ElseIfBlockA)”;
    }
    }
    }
    }
    class ElseIfBlockB implements TestInterface {
    public String Do(int x) {
    if (x >= 80) {
    return “A (by ElseIfBlockB)”;
    }
    else if (x >= 50) {
    return “B (by ElseIfBlockB)”;
    }
    else {
    return “C (by ElseIfBlockB)”;
    }
    }
    }
    (この発想とは別に、関数型インターフェースを使う方法もあると思います)

  2. > 関数名を配列に入れて順次コールしたかったと。
    そうそうそうなんスよ。
    ぽりもーふぃずむ? また調べてみます。
    クラス嫌い(´;ω;`)

  3. (誤) TestInterface testlist = {new IfBlock(), new ElseIfBlockA(), new ElseIfBlockB()};
    (正) TestInterface[] testlist = {new IfBlock(), new ElseIfBlockA(), new ElseIfBlockB()};
    でしたね。

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

CAPTCHA