How to access print method of class A in main method? Difference between objects a and b created in main method?
abstract class A {
void print() {
System.out.println("A");
}
}
class B extends A {
void print() {
System.out.println("B");
}
}
public class test {
public static void main(String[] args) {
B b = new B();
A a = new B();
b.print();
a.print();
}
}
In both cases,
overriden print()inclass Bwill be invoked.Case 1:
B b = new B();this case is straightforward. you create B object with B reference.
Case2:
A a = new B();Here, you are creating
B objectwithA reference. this is called polymorphicaly creating an object orcoding to an interface. as you have overriddenprint()inclass B, during run-time overloaded method ofclass Bwill be invoked.Other option:
create a method in class B which would invoke print method of class A using super keyword.