从基类Java访问子类方法
我有一个基类从基类Java访问子类方法,java,oop,inheritance,Java,Oop,Inheritance,我有一个基类 class C1 extends C { } 我有一个派生类 class C2 extends C1 { public void init() { } } 我的程序从类C1开始,我应该如何调用C2的“init()”方法?如果您的意思是希望通过实例化类C1的对象来访问类C2,则由于继承规则,您不能这样做。 编辑:我可以给你一个具体的例子:汽车是汽车的一个子类,因此当你创建汽车类时,你还不能拥有汽车,因为它取决于汽车的存在。 因此,在您的情况下,由于类C2取决于
class C1 extends C {
}
我有一个派生类
class C2 extends C1 {
public void init() {
}
}
我的程序从类C1开始,我应该如何调用C2的“init()”方法?如果您的意思是希望通过实例化类
C1
的对象来访问类C2
,则由于继承规则,您不能这样做。编辑:我可以给你一个具体的例子:汽车是汽车的一个子类,因此当你创建汽车类时,你还不能拥有汽车,因为它取决于汽车的存在。
因此,在您的情况下,由于类
C2
取决于类C1
的存在,您不能从类C1
调用类C2
的方法我相信,为了理解OOP是如何工作的,了解完整的继承概念是很重要的,因此我建议您看看能很好地解释这些概念的方法。这里有一个技巧,可以从父类调用
派生的类的方法:
public class Parent {
public Parent() {
speak(); // call private methods in constructor if you need
}
void speak() {
System.out.println("Parent speak implementation");
}
}
public class Child extends Parent {
public Child() {
super();
}
@Override
void speak() {
System.out.println("Child speak implementation");
}
}
public class Demo {
public static void main(String[] args) {
Parent c = new Child();
}
}
但是不推荐使用,您应该避免使用!正确的方法是在超类C1
中声明init()
方法,然后在派生类C2
中重写方法,并按如下方式调用它:
C1 c1 = new C2();
c1.init(); // will be called init method of C2 class
我看到您是从活动
类扩展的,我假设这是从Android
扩展的。如果是这样,我建议您尝试以下操作:
public abstract class C1 extends Activity {
protected abstract void init();
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_c1);
// your logic
}
}
public class C2 extends C1 {
@Override
protected void init() {
// your logic
}
}
<activity android:name=".C2">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
并在清单文件中声明您的主要活动
,如下所示:
public abstract class C1 extends Activity {
protected abstract void init();
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_c1);
// your logic
}
}
public class C2 extends C1 {
@Override
protected void init() {
// your logic
}
}
<activity android:name=".C2">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
你是说C2=new C2();c2.init()代码>不知道你想要什么。问题的标题和问题的主体在某种程度上并没有真正的联系。继承的全部要点是C1不知道C2的细节。您可以做的是在C1中创建一个抽象方法init,这样它就不再特定于C2了。是否可以使用其他方法,比如添加接口?对象实例必须仅来自C1。只有C2不扩展C1时才可能。或者做@valentin waeselynck指出的事情。