0

Can i get a proper expalantion about constructors in java??

8th Mar 2017, 6:22 PM
0000
2 Answers
+ 5
Constructor is a member function that is used to instantiate a class. Whenever you create an object of a class, the initialization of object can be done by constructor. Constructor name is same as class name. eg. class Sample { public int a; public Sample() { a=5; } public static void main(String arg[]) { Sample s1= new Sample(); } } This code creates an object S1 of class Sample and initialize S1.a=5 during it's creation.
8th Mar 2017, 6:30 PM
Sachin Artani
Sachin Artani - avatar
+ 2
A constructor lets you instantiate (create) an object from its class. your class is only a definition of an object. if you want to create an object to use it in your code, you can do so by calling a constructor. for example your class Cookie defines properties and behaviour (attributes and methods) of cookies. when you want to create a cookie to be used in your code you call the constructor. Cookie createdCookieObject = new Cookie(); now the createdCookieObject can be used in your code to behave as defined in the Cookie class.
8th Mar 2017, 11:59 PM
seamiki
seamiki - avatar