Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

programmer defined classes  RSS feed

 
bmel kaur
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i bought a book on java and came upon this codes:

public class Emp{
public Emp(){
init("unknown", "unknown", 0);
}
public Emp(String first,String last){
init(first,last, 0);
}
public Emp(String first,String last, int s){
init(first, last, s);
}

aren't constructors supposed to be built

Emp e1=new Emp();
Emp e2=new Emp(String first,String last);
Emp e3=new Emp(String first,String last,int s);

what's the difference between the two?
if there is no difference why were the constructors coded that way?
 
Wayan Saryada
Ranch Hand
Posts: 105
IntelliJ IDE MySQL Database Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think the book author trying to give an example of constructor chaining, where the constructor with less parameter is delegating the initialization process to the other constructors.
 
Jeroen T Wenting
Ranch Hand
Posts: 1847
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
that's no constructor chaining because no constructor is being called.
Instead there's some mystery "init" method being called from each constructor with different parameters.
 
Wayan Saryada
Ranch Hand
Posts: 105
IntelliJ IDE MySQL Database Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, you were right it was not a constructor chaining my tired eyes
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by bmel kaur:

what's the difference between the two?


The first shows how the constructors are defined, the second how they are used. You can only do the second, when you already have the first.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!