Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Constructor Declaration Confusion

 
Buburub
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When you mix a constructor declaration what are you really doing and why do
you do this?
Class1
Class2 extends Class1
public static void main(String args[ ])
Class1 c1 = new Class2( ) //why do you mix the constructor declaration?
Class2 c2 = new Class1( ) //why do you mix the constructor declaration?
Is this object reference conversion and casting?
Thanks in Advance!
 
sanjays samadder
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi what happens when you extend a class to another?
it gives a call to the default constructor of the super class.
here when you write class1 extends class2
it means that class1 has greater information than class2
that is just like a situation as with a float and an integer
a float is bigger thyan an integer.
here class1 is like a float but it is not excatly like primitive data conversion.class1 only has an outside reference to class2
the rule is
you can have a super class reference holding a sub class object the vice verca is not true.
why we do it?

look up the topic of Dynamic Method Despatch.
Thinking in java by bruce ekel will help
regards
 
Randall Twede
Ranch Hand
Posts: 4467
3
Java Python Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Buburub,
I hate to say this but, your name does not comply with the Javaranch naming guidelines which can be found at http://www.javaranch.com/name.jsp
please register again with a valid name.
 
Cindy Glass
"The Hood"
Sheriff
Posts: 8521
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Since Class2 extends Class1, Class2 is a particular sub-set or type of Class1.
When you say
Class1 c1 = new Class2();
You are saying "make a variable that can hold any type of Class1, then create a particular sub-set of Class1 (in this case Class2) and put it in that variable".
From an OO point of view this is considered good form because it allows you to make changes later (like using Class3, another sub-set of Class1 instead) to what you put in the variable without having to worry about everyplace that variable is used. If you had made the variable a Class2 some of the uses of it might not handle a Class3 without modifications. But since you used a Class1 and BOTH cases fit into it - all is good.
The second example you show of course will not work.
All squares are rectangles but not all rectangles are squares.
All Class2's are Class1's but not all Class1's are Class2's.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic