0
Can anyone explain why I need to create a constructor at all when I can just make an regular object and do the same things?
2 Antworten
+ 2
a constructor is always needed if you want to create a object. It becomes important if you create objects that needs specific fields
E.g. a person usually has a name. then you can write a constructor that looks like this :
public Person (String name){
this,name=name;
}
to ensure that every person gets a name on creation.
+ 1
Sometimes you will need to pass parameters to initialize some of the object fields on creating.
You may use the default constructor which accepts no parameters and you don't even need to write it in your class code. Java puts it there hidden for you.