+ 2

Java - constructor , someone explain from start to bottom with examples please :)

So I recently started learning Java oop and (about 2 weeks ago) and there's something that I don't really understand: 1) what's the difference between constructor and a method (besides that a constructor uses the name of a class) 2) how to use a constructor 3) And when is it really needed. I tried to understand constructor from many youtube tutorials but every time I just end up memorizing it and not really understanding. Thank you in advance :)

23rd Mar 2017, 9:39 PM
Tornike Shelia
Tornike Shelia - avatar
4 odpowiedzi
+ 15
1) Constructors are used to create objects. constructor doesn't have any return type like other methods (not even void) 2) See the explanation of Tomas Barra, it's quiet well formed 😊 In addition to this: In Java, if you don't even define a constructor in your class, a default / no-arg constructor will work. A default constructor only creates the object. You'll have to assign the values manually. Student s1 = new Student(); s1.name= "Peter"; s1.age = 18; // Student() is default constructor 3) You can't create any object without calling a constructor. So whenever an object creation is required, constructor call is mandatory.
23rd Mar 2017, 10:15 PM
Shamima Yasmin
Shamima Yasmin - avatar
+ 11
When you create a class you would like to instantiate it to create objects from it. This can be done via the "new" keyword. After this keyword you have to declare which constructor you would like to use to initialize the new object. You have to set constructor parameters too. After that the object created you can call it's method. Constructors cannot be called on an object, it is called only instantiation.
23rd Mar 2017, 9:52 PM
Tamás Barta
Tamás Barta - avatar
+ 10
Example: public class Person { private String name; public Person(String name) { this.name = name; } public String getName() { return name; } } In this example you declare the Person class which has only one attribute: name. When you create a concrete person, you have to declare it's name. That is why it's constructor has a name parameter which initializes the object name property. You have to use this constructor to create instance: Person p = new Person("Tornike Sheila"); After that you can call it's method: System.out.println(p.getName());
23rd Mar 2017, 9:58 PM
Tamás Barta
Tamás Barta - avatar
0
Thanks very good explaining in your example , I'm starting to understand it slowly. :d
23rd Mar 2017, 10:07 PM
Tornike Shelia
Tornike Shelia - avatar