What a constructor do ?

Hum.. I always forget the function of a constructor because I don’t have the custom to use.

For this reason, I will put here some tips:

A constructor  is a method with instructions that will execute ALWAYS  when will instantiated a object of this class.

Like this:

  • Class MyClass.java
 public class MyClass {

public MyClass() { //this is the constructor method
System.out.println(“Hello World !”);
}  }

In the constructor method will be wrrte “Hello World !”

So… when you call this class, the constructor will be execute.

 

  • Class Test.java
 public class Test {

public static void main(String args[]) {
MyClass Obj1 = new MyClass();
}
}

It’s simple no ? It is just a method that will be execute before others methods when you call this class.
Bye bye !

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.