Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Unable to understand . help Needed (inheritance)

 
Anshul Mathur
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hello all

I have a problem with the following code unable to understand the concept
why

first f = new second(); // Works Fine
second s = new first(); // Does not work gives Error

Thanks
Anshul Mathur


Code follows


[ May 23, 2004: Message edited by: Barry Gaunt ]
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You know second isa first because second extends first.

Is first necessarily a second?
 
Anshul Mathur
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks.
 
Voggy Horla
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i always determine by this
A = new B =>is that capatabled with that
B instanceof A
that might be good to you!
 
Wendal Park
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Or you can read it this way:

class B extends A { ... } => Read as "Class B is an A" ...
But you should also know A may not be a B.

Those "is-a" and "has-a" relationship would help your understanding ...
 
Preetham Chandrasekhar
Ranch Hand
Posts: 98
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
second is a first....since second extends first....
but .....
obviously
first is NOT a second....so your second statement wont work
Preetham
SCJP 1.4
 
Marlene Miller
Ranch Hand
Posts: 1392
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello Anshul. I'd like to try to explain the concept.

second s = new first(); // Does not work gives Error

s is the name of a variable. A variable has a type and a value.

The type of the variable s is second.

The value of the variable s is a reference to an object. The variable s holds a reference to an object.

The object also has a type, which might be different from the type of the variable. The type of the object must be ***the same as or a subtype of*** the variable. Why?

class first { int x; void m() {} }
class second extends first { int y; void n() {} }

f.x and f.m() make sense if f refers to an object of type first or second. Both objects have members x and m().

s.y and s.n() make sense only if s refers to an object of type second, not type first. Only an object of type second has members y and n().
[ May 25, 2004: Message edited by: Marlene Miller ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic