关于访问 child 的变量或方法

About accessing child's variables or methods

这里我举个例子。 我知道 Thor Class 中的那些方法将覆盖 Avengers Class 中的方法。 (我将跳过方法的主体)

Class Avengers{

   void hit(){
   }
   void walk(){
   }
}

Class Thor extends Avengers{

   void hit(){
   }
   void walk(){
   }
   void thunderSkill(){
   }
} 

这是主要的。

public static void main(String[] args) {
Avengers thor = new Thor();
}

如果我这样做,使用 'thor' 实例,我可以访问那些 hit() 方法和 walk() 方法。但是我无法访问 thunderSkill() 方法。我意识到只能访问覆盖方法。我的问题是,在 Parent class、Avengers class?

中,是否有任何方法可以在不覆盖 thunderSkill 的情况下访问 thunderSkill 方法

所以如果它有其他英雄,比如雷神、钢铁侠、美国队长等,他们 都应该有自己独特的方法。如果我想通过实例访问它,是否所有这些独特的方法都需要在 parent class、Avengers class 中? (我正在尝试将实例的数据类型设置为 'Avengers',因此我可以轻松处理 'parameter' 和 'argument'。)

我是 Java 的新手,请帮助我:)

谢谢大家!!

父 class 引用无法访问子 class 方法。如果使用 Parent class 引用,则只能调用覆盖的方法。

如果您想使用子 class 方法,有两种选择。 选项 1:在 Overridden 方法中调用子方法。 (简单的) 选项 2:您可以将 Parent class 引用转换为 Child Class 对象,然后您可以调用子 class 方法。这是选项 2 的示例代码。

我建议您阅读有关继承的 java 文档。 https://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html

public class Parent {

    public void canSpeak() {
        System.out.println("I can speak");
    }

    public static void main(String[] args) {

        Parent p = new Child();
        p.canSpeak();

        // p.canRead()  // can not be accessed. because the refernece is parent.
        // if you want to access the canRead() method in child class, then you need to case the object.

        Child c = (Child)p;
        c.canRead();
    }
}

public class Child extends Parent {
    /**
     * This is the overridden method.
     */
    @Override
    public void canSpeak() {
        System.out.println("I can speak");
    }
    /**
     * Only child can read.
     */
    public void canRead() {
        System.out.println("I can read");
    }
}

你能做的就是使用接口。例如,定义:

public interface Superhero {
    void superpower();
}

然后让 Thor 实现 Superhero,并像 thunderSkill 所做的那样实现 superpower

为了让各位大侠拥有更多的力量,可以多出一个界面:

public interface Superpower {
    void useSuperpower();
}

然后让 Thunderskill 实施 Superpower,并让 Avenger class 拥有一个 List<Superpower>,然后您可以相应地填充它。