从子类调用方法

时间:2018-05-07 07:35:24

标签: java methods casting

我正在尝试这样的事情:

public class Dog {
}

public class Cat extends Dog {
    private void mew() {
    }
}

Dog d = new Dog();
d.mew();

在运行时期间,由于其他方法,d将包含cat对象,但我无法编译。

3 个答案:

答案 0 :(得分:1)

应该使用Dog实例(或Cat实例{/ 1}}初始化Stone

SpecialStone

然后你可以在你的Stone s = new SpecialStone(); 上调用这个方法(这只有在你按子类初始化父方法时才有效):

SpecialStone

另一种方法是使用多态:

if (s instanceof SpecialStone) {
   (SpecialStone)s.specialMethod();
}

但它会为public class Stone { public void specialMethod() { } } public class SpecialStone { @Override public void specialMethod() { } }

的每个实例添加specialMethod

答案 1 :(得分:0)

它的另一种方式。

if( $theme == null ) { return redirect('plugins'); } elseif( $theme != null ) { foreach($this->predefinedArray as $value) { $request->session()->put('chosen_theme.' . $value, $theme->$value); } $request->session()->put('chosen_theme.composer_package', $theme->productable->composer_package); return redirect('plugins'); } 是一个父类,所以它实际上并不知道某个类Dog扩展了它,并且它不知道扩展它的类的方法。

然而Cat扩展了Cat,它知道Dog +自己的方法的所有非私有方法。

因此,您无法从Dog致电mew()

答案 2 :(得分:0)

使用定义“Stone”方法的接口,然后对NormalStone或SpecialStone使用不同的实现。 看我的例子:

public interface Stone {
    int getValue(); 
}

public class NormalStone implements Stone {

    @Override
    public int getValue() {
        return 1;
    }
}

public class SpecialStone implements Stone {


    @Override
    public int getValue() {
        return 100;
    }
}

public class Game {

    public static void main(final String[] args) {
        final List<Stone> stones = new ArrayList<>();
        stones.add(new NormalStone());
        stones.add(new SpecialStone());

        for (final Stone stone : stones) {
            System.out.println(stone.getValue());
        }

    }
}
相关问题