Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Variable and Instance

 
Chuan Chung Tsao
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public class A{
int i;
public void m(){}
}
public class B extends A{
int i;
public void m(){}
public static void main(String[] arg){}
}
if we in main method add:
a) A a = new A();
b) B a = new A();
C) A a = new B();
d) B a = new B();
and add respectively:
a.i;
a.m();
how do we to understand its result, and if we announce m() and i as static in the different class, what is its result? And how could we remember it easily? Thank you.
 
Marilyn de Queiroz
Sheriff
Posts: 9065
12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I don't understand your question, or are you asking multiple questions?
 
Pratibha Malhotra
Ranch Hand
Posts: 199
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Chuan Chung Tsao
Following is a modified version of your program so as to make u understand logic well.......
class A
{int i = 10;
public void m()
{System.out.println("In m() of Super Class");}
}
public class B extends A
{int i = 20;
public void m()
{System.out.println("In m() of Sub Class");}
public static void main(String[] args)
{ A a = new A();
System.out.println("value of i :: "+a.i);
a.m();
}
}

1>
A a = new A();
value of i :: 10
In m() of Super Class
Logic :: Instance of Superclass A is created and thus variable and method of superclass are accessed.
*********************************************
2>
A a = new B();
value of i :: 10
In m() of Sub Class
Logic ::
Dynamic Method dispatch is what is happening here.
Instance created is of type Class A but is pointing towards Class B. As a result of which method of class B ie subclass is accessed.
Variable accessed however of superclass as variables are not overrided in case Dynamic Method dispatch.
*********************************************
3>
B a = new B();
value of i :: 20
In m() of Sub Class
Logic :: Instance of Subclass B is created and thus variable and method of subclass are accessed.
*********************************************
4>
B a = new A();
Compile Time Error :: Incompatible types
B a = new A();
Logic :: Casting is required.
Solution -> B a = (B) new A();
This however will again cause ClassCast Excetion as instance of Superclass can not be casted to instance of Subclass. Converse however is correct.
Hope this clarifies your doubt ... In case u need more information just let me know....
 
Pratibha Malhotra
Ranch Hand
Posts: 199
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

In case u need more info on Dynamic Dispatch
Dynamic Inheritance in Java!
Have a look at
http://www.cyberdyne-object-sys.com/oofaq2/DynInh.htm
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic