0

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?

Abhi Nandan
  • 195
  • 3
  • 11
  • using `super`? ie. in `c2.m1()` you call `super.m1()` it'll automatically calls `m1()` in c2's parent. [related](http://stackoverflow.com/questions/3767365/super-in-java) – Bagus Tesa Dec 02 '16 at 09:45
  • 1
    No you cannot. Think of this case if both C2 and C3 define a method `m3()` then which method should java invoke when you call `c1.m3()`? `C2.m3()` or `C3.m3`? – diufanman Dec 02 '16 at 09:55

1 Answers1

1

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.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • Thanks @Bathsheba. I was looking for some alternative. The purpose is logically segregating the methods in three different classes and invoking all from the same point. Doesn't look feasible. :( – Abhi Nandan Dec 02 '16 at 10:10
  • I've added an alternative approach at the end. – Bathsheba Dec 02 '16 at 10:12