+ 17
What is a constructor? How is it used?
8 Answers
+ 13
thank you
+ 7
When you want to use an object, you need to construct it. In other words, you use the constructor of an object to initialize it.
+ 4
hi,
a constructor is used to initialize the attributes of a class when you create an object. Let's you have a class like this:
class person
{
String name;
String surname;
int age;
//constructor
public class(String name, String Surname, int age)
{
this.name = name;
this.surname = surname;
this.age = age;
}
}
now when we create an object:
person friend = new person("Jon", "Doe",18); //<<<constructor
the values we passed in the brackets will be assigned to name, surname And age. so if we do:
System.out.println(friend.name);
it will print "Jon".
+ 4
@Edi
Which one is the main class?
class person
{
String name;
String surname;
int age;
or.... the second one
+ 3
constructor is the first block of code will work when you create a new object from the class that the constructor represent it, in Java by default for any class you create there's a constructor without parameters, so if you create any parameterized constructor it's preferred to create an empty parameters constructor.
+ 2
you can think of a constructor as an initializer. whenever an object is created with certain values . the constructor helps in initializing it with the associated values.
+ 1
you declared a wrong constructor name.
you declared "public class" instead of "public person"
0
You is the first block of code which will be operated as soon as an object is created of any class.