Although it is really a
FieldShadowing_2
underneath, the
FieldShadowing_2
is pretending to be a
FieldShadowing_1
, which cannot
display()
.
This is an example of
inheritance and
abstraction:
FieldShadowing_2
inherits FieldShadowing_1
.
The variable
b
is an
abstraction of
FieldShadowing_2
because it is stored as a
FieldShadowing_1
.
Here is a rewritten version demonstrating more situations that do and don't have errors:
(I have changed the class names because
FieldShadowing_1
is not a very descriptive class name, and because this code does not actually demonstrate
shadowing, which is something else entirely!)
public class A
{
public String getName() { return "A"; }
}
public class B1 extends A
{
public void display()
{
System.out.println("Check");
}
}
public class B2 extends A
{
public void doNothing()
{
}
}
public static void main(String[] args)
{
B b1 = new B1();
B b2 = new B2();
A a1 = b1;
A a2 = b2;
System.out.println(b1.getName());
System.out.println(b2.getName());
System.out.println(a1.getName());
System.out.println(a2.getName());
b1.display();
b2.display();
a1.display();
a2.display();
b1.doNothing();
b2.doNothing();
a1.doNothing();
a2.doNothing();
}