Vous êtes sur la page 1sur 8

16/9/2015

JavaConstructorChainingwithexample

Beginner'sBook

CoreJava
OOPsConcepts
JavaCollections
JSP
JSTL
InterviewQuestions
JSPInterviewQ
JUnitInterviewQ
ServletInterviewQ

JavaConstructorChainingwithexample
OOPsConcept
CallingaconstructorfromtheanotherconstructorofsameclassisknownasConstructorchaining.We
willunderstandthiswiththehelpofbelowprogram.

ExampleProgram
InthebelowexampletheclassChainingDemohas4constructorsandwearecallingoneconstructor
fromanotherusingthis()statement.Fore.g.inordertocallaconstructorwithsinglestringargumentwe
havesuppliedastringinthis()statementlikethis(hello).
Note:this()shouldalwaysbethefirststatementinconstructorotherwiseyouwillgetthebelowerror
message:
Exceptioninthread"main"java.lang.Error:Unresolvedcompilationproblem:
Constructorcallmustbethefirststatementinaconstructor

CompleteCode:
packagebeginnersbook.com;
publicclassChainingDemo{
//defaultconstructoroftheclass
publicChainingDemo(){
System.out.println("Defaultconstructor");
}
publicChainingDemo(Stringstr){
this();

System.out.println("Parametrizedconstructorwithsingleparam");
}
publicChainingDemo(Stringstr,intnum){
//ItwillcalltheconstructorwithStringargument

this("Hello");

System.out.println("Parametrizedconstructorwithdoubleargs");
}
publicChainingDemo(intnum1,intnum2,intnum3){

//Itwillcalltheconstructorwith(String,integer)arguments
this("Hello",2);
System.out.println("Parametrizedconstructorwiththreeargs");
http://beginnersbook.com/2013/12/javaconstructorchainingwithexample/

1/8

16/9/2015

JavaConstructorChainingwithexample

}
publicstaticvoidmain(Stringargs[]){
//CreatinganobjectusingConstructorwith3intarguments
ChainingDemoobj=newChainingDemo(5,5,15);
}
}

Output:
Defaultconstructor
Parametrizedconstructorwithsingleparam
Parametrizedconstructorwithdoubleargs
Parametrizedconstructorwiththreeargs

YouMightLike:
JavaDefaultconstructorwithexample
ConstructorOverloadinginJavawithexamples
Javaparameterizedconstructorwithexample
JavastaticconstructorIsitreallyPossibletohavetheminJava?
JavaConstructorinInterface?
ConstructorsinJavaAcompletestudy!!
Javaprivateconstructorexample
chainingconstructor
PreviousArticleNextArticle
2commentsaddone
SeanOctober22,2014,9:26AM
Butwhatisthepointofconstructorchaining?
i.e.whywouldIeverwanttodothis?
Reply
KahmaliNovember28,2014,4:10PM
http://beginnersbook.com/2013/12/javaconstructorchainingwithexample/

2/8

16/9/2015

JavaConstructorChainingwithexample

Thecodeexamplesheprovidedarefairlyuseless.Notsurewhytheauthordidntusethe
paramsinanyoftheconstructors.Therealpurposeissothatyoucanpassparameters
throughabunchofdifferentconstructors,butonlyhavetheinitializationdoneinasingle
place.Thisallowsyoutomaintainyourinitializationsfromasinglelocation,while
providingmultipleconstructorstotheuser.Ifwedontchain,andtwodifferentconstructors
requireaspecificparameter,youwillhavetoinitializethatparamtwice,andwhenthe
initializationchanges,youllhavetochangeitineveryconstructor,insteadofjusttheone.
Reply
LeaveaComment
Name*
Email*
Website

Comment
Submit

ConfirmyouareahumanBeing
Notifymeoffollowupcommentsviaemail
OOPsConcepts
Methodoverloading
Methodoverriding
OverloadingvsOverriding
Constructor
Defaultconstructor
Parameterizedconstructor
Privateconstructor
Constructorininterface
Constructorchaining
staticconstructor
Constructoroverloading
Aggregation
Association
OOPsbasics
Polymorphism
Typesofpolymorphism
Inheritance
Typesofinheritance
http://beginnersbook.com/2013/12/javaconstructorchainingwithexample/

3/8

16/9/2015

JavaConstructorChainingwithexample

Hybridinheritance
Hierarchicalinheritance
Multilevelinheritance
Multipleinheritance
Encapsulation
Staticanddynamicbinding
Staticclass
Staticmethods
Staticvariables
Staticimport
Staticconstructor
Innerclasses
Abstractclassandmethods
Interface
Abstractclassvsinterface
Accessmodifiers
Packages
MORE...
Stringhandling
Exceptionhandling
Multithreading
JavaI/OTutorial
JavaSerialization
RecentlyAdded..
JSONTutorial
JavaRegularExpressionsTutorial
JavaEnumTutorial
JavaAnnotationsTutorial

http://beginnersbook.com/2013/12/javaconstructorchainingwithexample/

4/8

16/9/2015

JavaConstructorChainingwithexample

http://beginnersbook.com/2013/12/javaconstructorchainingwithexample/

5/8

16/9/2015

JavaConstructorChainingwithexample

Beginnersbook.com
LikePage

5.8klikes

Bethefirstofyourfriendstolikethis

FollowMeonGoogle+
Chaitanya Singh
Ikuti
1.724 pengikut

JoinUsOnGooglePlus
BeginnersBook
Ikuti

+1

+ 2.568

http://beginnersbook.com/2013/12/javaconstructorchainingwithexample/

6/8

16/9/2015

JavaConstructorChainingwithexample

ReferenceLinks
http://beginnersbook.com/2013/12/javaconstructorchainingwithexample/

7/8

16/9/2015

JavaConstructorChainingwithexample

DownloadJava
EclipseIDEDownloads
JavaDocumentation
JavaEE5Tutorial
JavaEE6Tutorial
JavaEE7Tutorial
JavaSE6.0APISpecification
JavaSE7.0APISpecification
JavaServerPagesJSP
PopularTutorials
CoreJavaTutorial
JSPTutorial
JSTLTutorial
JavaCollectionsTutorial
ServletTutorial
CTutorial
JavaStringTutorial
Friends&Links
FromDev.com
DZoneFreshLinks
MostVisited
JavaInterview
JSPInterview
JavaMultithreadingInterview
JavaCollectionsInterview
ServletInterview
JUnitInterview
AboutChaitanyaSingh

FounderofbeginnersBook.com,lovesJavaandopensourcestuff.BeginnersBook.comisa
techblogwherehesharestutorialsonprogramming(Java,C,CPP),WordPress,SEOandweb
development.
Connecton
Copyright20122015BeginnersBookAllRightsReserved||Sitemap

http://beginnersbook.com/2013/12/javaconstructorchainingwithexample/

8/8

Vous aimerez peut-être aussi