简体   繁体   English

Java:从父级访问Child类方法

[英]Java: accessing Child class methods from parent

Is it possible to access the child class method from parent class? 是否可以从父类访问子类方法?

public class C1 {
    public C1(){
         System.out.println("Constructor C1");
    }
}

public class C2 extends C1{
    public void m1(){
         System.out.println("print from m1");
    }
}

public class C3 extends C1{
    public void m2(){
         System.out.println("print from m2");
    }
}

public class TestMain{
    public static void main(String[] args){
         C1 c1 = new C1();
    }
}

Is there anyway to access c1.m1() & c1.m2() without initializing for child class? 无论如何,是否无需初始化子类即可访问c1.m1()和c1.m2()?

No there isn't: c1 is a reference referring to an object of type C1 . 不,没有: c1是引用类型C1的对象的引用。 There's no conversion that you can use to fool Java into thinking that it's a C2 or a C3 . 没有任何可用来欺骗Java的转换,以至于认为它是C2C3

What you would normally do is to define an abstract function mSomething in C1 , implement that function in the child classes and use something like 通常要做的是在C1定义一个abstract函数mSomething ,在子类中实现该函数并使用类似

C1 c = new C2();

c.mSomething() would then call, polymorphically , the required function in the child class. 然后, c.mSomething()将在子类中多态调用所需的函数。

Another alternative would be to make m1 and m2 static , and have them take a C1 instance as a parameter. 另一种选择是使m1m2 static ,并使它们以C1实例作为参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM