This week's book giveaways are in the Cloud and AI/ML forums.
We're giving away four copies each of Cloud Native Patterns and Natural Language Processing and have the authors on-line!
See this thread and this one for details.
Win a copy of Cloud Native PatternsE this week in the Cloud forum
or Natural Language Processing in the AI/ML forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Devaka Cooray
  • Liutauras Vilda
  • Jeanne Boyarsky
  • Bear Bibeault
Sheriffs:
  • Paul Clapham
  • Knute Snortum
  • Rob Spoor
Saloon Keepers:
  • Tim Moores
  • Ron McLeod
  • Piet Souris
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Tim Holloway
  • Frits Walraven
  • Ganesh Patekar

Assigning base class object to sub class reference ?

 
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?

PLEASE HELP ME

Thanks
Arulraj
 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
arulraj michealraj
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks.............
 
author
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!