Constructor?

0 Casper Hollemans · September 17, 2015
Hey I'm watching Bucky's java vid's and he did explain constructors but I don't get it yet properly enough.
I mean you have a class then you make a "constructor" with the same name and tell the class what to do with things.
Why not in the class?
And could someone give a simple explanation?

Thank you in advance. :)

-Greets

Post a Reply

Replies

Oldest  Newest  Rating
+1 Tóth Bence · September 17, 2015
If you create an instance of your class like

MyClass A = new MyClass(/*parameters*/);

it runs the constructor. the things you write in the brackets are the parameters of your constructor if you have any.
public class MyClass {
public MyClass(/*here you can set the parameters*/)
{
//this is the constructor
}
}

example:

public class Student
{
String name;
int age;
public Student(String name, int age)
{//the this. indicates tha class is variable
this.name=name;
this.age=age;
}
}


another class e.g. main

public static void main(String[] args) {
        Student A = new Student("Name", 20);
    }

i hope i helped :)
0 Casper Hollemans · September 17, 2015
Thanks man, you made it pretty clear for me :D
  • 1

Java / Android Development

107,052 followers
About

Very popular language used to create desktop applications, website applets, and Android apps.

Links
Moderators
Bucky Roberts Administrator