There is a parent class that is an abstraction when creating instances of child classes. How can I access the methods of the child class from the parent instance?

class A { //some code } class B extends A { private int i = 10; public void go() { //some code } } 

Main class:

 A a = new B(); a.go();//error 
  • I think in any way, although I also just learn - danilshik
  • four
    ((B) a) .go (); - Serodv
  • Thanks to all! I thought there is another way that I do not know, but I don’t see. In the answers I did not learn anything new for myself, but nevertheless I will note one as correct. - JavaJunior pm

3 answers 3

Bring the type of a variable to a child class:

 A a = new B(); ((B) a).go(); 

The problem is that a variable can store an object of class A and its other heirs, which will not have a go method. Therefore, it may be necessary to first check whether the variable contains an object of the required class:

 if(a instanceof B) { B b = (B) a; b.go(); } 

In general, the very fact that you needed a type conversion is a reason to think and work on the logic of the code. Why is a variable declared with type A ? Will there always be a class B object? Is it necessary to transfer the method to the parent class? Wouldn't it be better to create a method in A and override its behavior in B ?

    If all child classes have such a method, then you can declare it in the base class.

     abstract class A { public abstract void go(); } 

      If there is no method in class A, then you cannot call a method of another class from it. But if you add a method with the same signature and return value to the class A, then in B this method will be blocked, and therefore caused due to polymorphism. Method and class A can be made abstract if there is no common default implementation for subclasses, and therefore subclasses will have to write their implementation. If class A is not abstract, but contains a method that is overlapped in a subclass, then the method call will come from the subclass, due to the same polymorphism, but in this case the subclasses are not required to implement or override the common method that will have default implementation.

      For a better understanding of abstract classes, you can read this answer.