#help about constructor basic understanding

9 messages · Page 1 of 1 (latest)

fast zenith
#

I am new in java, now im getting in to oop section, then i met with this constructor. ,

its been two weeks for me to getting understand how this java constructor works

And why its written in such manner

And what is exactly constructor do step by step when we call them

Also what is the anaogy of a constructor in real life

Here an example copy from web, you might tell me the work flow of a constructor in java


//Let us see another example of default constructor  

//which displays the default values  

class Student3{  

int id;  

String name;  

//method to display the value of id and name  

void display(){System.out.println(id+" "+name);}  

  

public static void main(String args[]){  

//creating objects  

Student3 s1=new Student3();  

Student3 s2=new Student3();  

//displaying values of the object  

s1.display();  

s2.display();  

}  

}  

gray dockBOT
#

This post has been reserved for your question.

Hey @fast zenith! Please use /close or the Close Post button above when you're finished. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.

TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.

sly nimbus
#

a constructor, in concept, is a special method that specifies how to make a certain object

gray dockBOT
sly nimbus
#

try checking out the "classes" section there, there's a part on constructors

tall kelp
# fast zenith I am new in java, now im getting in to oop section, then i met with this constru...

By default, classes will always generate a default constructor (one that takes no parameters like you see above). It is identical to doing the following:

public Student3() {}

If you make a different constructor (such as one with a parameter), then it will override this default constructor and not allow for it to be used:

private String name;
public Student3(String name) {
  this.name = name;
}

public static void main(String[] args) {
  // now this is invalid
  Student3 student1 = new Student3();
  
  // and this is valid
  Student3 student2 = new Student3("john");
}
fast zenith
# gray dock

@fast zenith i have read it, gave me a little spark to understanding this, little but valuable, i Will just do read More, thhank you

fast zenith