This week's book giveaway is in the OO, Patterns, UML and Refactoring forum.
We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line!
See this thread for details.
The moose likes Java in General and the fly likes Assigning base class object to sub class reference ? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

JavaRanch » Java Forums » Java » Java in General
Bookmark "Assigning base class object to sub class reference ?" Watch "Assigning base class object to sub class reference ?" New topic

Assigning base class object to sub class reference ?

arulraj michealraj

Joined: Mar 02, 2005
Posts: 28
Hi ,

I have one doubt in the following code.
class A
class B extends A.

1. A objA=new A();
2. A obj=new B();
3. B objB=new A();

The first two line will work without giving any error. but for line 3, it will say compile time error.

May i know the reason why this is giving an error?


Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14950

The most important thing to remember about inheritance is that it is an "is a" relationship. So, an instance of a subclass is an instance of its superclass too.

Just like a dog is an animal, and a cow is an animal. Ofcourse it only works one way; if a dog is an animal, it doesn't mean that an animal is a dog.

In your code, an instance of B is an instance of A, so line #2 is no problem. However, an A is not necessarily a B, so line #3 doesn't work.

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
arulraj michealraj

Joined: Mar 02, 2005
Posts: 28
Ilja Preuss

Joined: Jul 11, 2001
Posts: 14112
And the technical reason is that Java is a statically typed language - that is, the compiler uses the type information to check at compile time whether a method call is possible.

Imagine that class B declared a new method that isn't available in class A. Consequently, you could call that method on any B reference. If such a reference could point to an instance of A, the compiler couldn't know whether the object actually *knows* the method you are trying to call.

Google for "Liskov Substitution Principle" for more on this.

The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
I’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link:
subject: Assigning base class object to sub class reference ?
It's not a secret anymore!