使用接口参考从另一个类继承属性

时间:2019-03-22 18:21:06

标签: java inheritance

我不确定如何准确表达我的问题。 因此,我有一个接口引用,并且正在创建一个新对象。新对象显然实现了所述接口。初始类继承另一个类。该子类继承了超类。但是,如果不先转换引用,就无法从main方法访问超类的数据。我将在下面显示一个示例

    public class a {

    public int getSomeData1() {
        return someData;
    }
}

public class b extends a implements someInterface {
    // Some behavior. 
}

public class c extends b implements someInterface {
    // Some behavior. 
}

public class Main {

    public static void main(String[] args) {
        someInterface obj = new b();

        obj.someData1(); // I cannot access someData1(). 

        c anotherObj = new c();

        c.getSomeData1(); // This works however. 
    }
}

如何让obj.someData1()实际上从a类获取数据,而不是将其强制转换为a

1 个答案:

答案 0 :(得分:0)

只需记住以下规则:编译器允许的方法调用完全基于引用的声明类型,而与对象类型无关。

如果不是很清楚,这是该规则的另一种形式:左侧的内容定义了可以调用的方法,无论右侧的内容如何:)

以下是一些例子,以使其更清楚:

public interface Animal {
    void voice();
}

public class Dog implements Animal {
    public void voice() {
       System.out.println("bark bark");
    }

    public void run() {
        // impl
    }
}

当您创建这样的狗时:

Animal dog1 = new Dog();

引用类型为Animal定义了允许您调用的方法。所以基本上您只能致电:

dog1.voice();

当您创建这样的狗时:

Dog dog2 = new Dog();

引用类型为Dog,因此您可以调用:

dog2.voice();
dog2.run();

在拥有类继承时,不仅在实现接口时,该规则也会保留。假设我们有类似的东西:

public class SpecialDog extends Dog {
    public void superPower() {}
}

这些是您可以称之为的示例:

Animal dog1 = new SpecialDog();
dog1.voice(); // only this

Dog dog2 = new SpecialDog();
// here you can call everything that Dog contains
dog2.voice();
dog2.run();

SpecialDog dog3 = new SpecialDog();
// here you can call all 3 methods
// this is the SpecialDog method
dog3.superPower();

// those 2 are inherited from Dog, so SpecialDog also has them
dog3.voice();
dog3.run();

在其他情况下,您需要上调/下调才能调用某些特定方法。

Happy Hacking :)

相关问题