Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Real vs Apparent classes in Java

Tags:

java

class A { public static void main(String[] args) 
{ A a = new A(); 
  B b = new B(); 
  A ab = new B(); 
  System.out.format("%d %d %d %d %d %d", a.x, b.x, ab.x, a.y, b.y, ab.y); } 
  int x = 2; 
  int y = 3;
  A(int x) { this.x = x; } 
  A() { this(7); } } 

class B extends A { 
  int y = 4;
  B() { super(6); 
  }

Hey all, I was just looking through some examples from my course and came across this problem that stumped me.
I realize that that this code should print out "7 6 6 3 4 3"

But why is ab.y equal to 3? Isn't the "real" type of object ab of class B? Which then would lead me to believe that ab.y be 4?

like image 388
Kevin Zhou Avatar asked Sep 28 '10 01:09

Kevin Zhou


People also ask

What is the apparent type of an object?

As a consequence of there being a type hierarchy, a variable of one type may refer to an object whose actual type is one of that type's subtypes. The type given when the variable was declared is referred to as the apparent type of the object referred to by the variable.

What are different types of hierarchy in Java?

On the basis of class, there can be three types of inheritance in java: single, multilevel and hierarchical.

What is default type of class in Java?

So, a Java class is by default package-private.

Are classes private by default?

The default access specifier is an important differentiate between classes and structs. It is public by default for structs and private by default for classes.


1 Answers

Because you are accessing the fields directly, and not via getter methods.

You cannot override fields, only methods.

Class B has a field y in addition to the one in parent class A. The two fields do not interfere with each-other, which one gets picked up is determined at compile-time (by the type known to the compiler).

If you say

   A ab = new B(); 

then

  ab.y

will be compiled to look at the field y declared in class A. This is not dispatched at runtime to the real instance's class. It would be the same with a static method.

If you do

    B ab = new B();

then you get the field in class B.

like image 168
Thilo Avatar answered Sep 22 '22 12:09

Thilo