| Author |
doubt in inheritance
|
arulraj michaelraj
Greenhorn
Joined: Mar 07, 2007
Posts: 14
|
|
i am arulraj and have a doubt in inheritance.. please see the following example. class A { int a=10; } class B { int a=20; } A objA=new A(); B objb=new B(); objA=objb; // 1 objb=objA // 2 it says compiler an error. In the above example , if you assign a subclass object to a superclass object, the program compiles and executes... if you do reverse operation (assign a superclass object to subclass object), the compiler says an error.... 1. Can you pleas explain it why this one is not allowed? 2. System.out.println("objA.a:"+objA.a); it prints value 10. May i know why it gives the value 10 instead of 20? 3.. what is difference between object and object reference?
|
 |
marc weber
Sheriff
Joined: Aug 31, 2004
Posts: 11343
|
|
"arulrajjj michaelrajjj," Welcome to JavaRanch! Please revise your display name to meet the JavaRanch Naming Policy. To maintain the friendly atmosphere here at the ranch, we like folks to use real (or at least real-looking) names. You can edit your display name here. Thank you for your prompt attention! -Marc
|
"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
|
 |
arulraj michaelraj
Greenhorn
Joined: Mar 07, 2007
Posts: 14
|
|
i am arulraj and have a doubt in inheritance.. please see the following example. class A { int a=10; } class B extends A { int a=20; } A objA=new A(); B objb=new B(); objA=objb; // 1 objb=objA // 2 it says compiler an error. In the above example , if you assign a subclass object to a superclass object, the program compiles and executes... if you do reverse operation (assign a superclass object to subclass object), the compiler says an error.... 1. Can you pleas explain it why this one is not allowed? 2. System.out.println("objA.a:"+objA.a); it prints value 10. May i know why it gives the value 10 instead of 20? 3.. what is difference between object and object reference?
|
 |
Jesper de Jong
Java Cowboy
Bartender
Joined: Aug 16, 2005
Posts: 12953
|
|
Inheritance indicates an "is a" relationship. An instance of a subclass is a specialized version of an instance of its superclass. It is easier to see if you use other names than "A" and "B" for your classes. For example: About question 2: Member variables cannot be overridden just like methods. About question 3: An object is "the thing itself" and a reference is something that points to the object. In Java, variables are references to objects (unlike for example C++ where variables hold the objects themselves). [ March 08, 2007: Message edited by: Jesper Young ]
|
Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
|
 |
arulraj michaelraj
Greenhorn
Joined: Mar 07, 2007
Posts: 14
|
|
|
thanks jesper....
|
 |
 |
|
|
subject: doubt in inheritance
|
|
|