public class A {
protected int x = 10;
A() {
System.out.println("Constructor A" ) ;
}
public void test() {
System.out.println(" A " );
}
public void Aex() {
System.out.println(" Aex " ) ;
}
public void testg() {
System.out.println("Hello");
}
}
public class B extends A {
B() {
System.out.println("Constructor B" ) ;
}
B(int num){
this.x = num ;
//System.out.println(this.x);
}
public void test() {
System.out.println(" B " );
}
public int getx() {
return this.x;
}
}
public class C {
public static void main( String [] args ) {
A a = new B();
//a.test();
a.Aex();
//a.testg();
B b = new B(5);
a = b;
a.test();
System.out.println( a.getx() ) ;
}
}
Class B inherits from class A and both have a method called test(). I can create a base class reference to a derived class object , so I create a reference A a = new B(); . When I call a.test() , the test() method of B is called which I understand , which helps me to prevent conditional statements in my code. But suppose B has another method called void getx() , and I want to call that method, I cannot call it with a base class reference , since the base class has no method called void getx() . So how is polymorphism useful in such a situation ? The only way to call getx is to create a reference of derived class and call getx().