Abhi Nandan
Abhi Nandan

Reputation: 195

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?

Upvotes: 0

Views: 5168

Answers (1)

Bathsheba
Bathsheba

Reputation: 234635

No there isn't: c1 is a reference referring to an object of type C1. There's no conversion that you can use to fool Java into thinking that it's a C2 or a C3.

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 c = new C2();

c.mSomething() would then call, polymorphically, the required function in the child class.

Another alternative would be to make m1 and m2 static, and have them take a C1 instance as a parameter.

Upvotes: 1

Related Questions