Constructors in Java
Overview
Types of Constructors
- Default Constructors - These are default constructors who doesn't have any arguments
Dog myDog = new Dog();
public Dog() {
// Write the code that will execute automatically when an object of Dog is created
}
- Parameterized Constructor
Dog bravo = new Dog("Bravo");
public Dog(String name) {
this.name = name;
}
Dog newDog = new Dog(5);
public Dog(int age) {
this.age = age;
}
Dog jackie = new Dog("Jackie", 3);
public Dog(String name, int age) {
this.name = name;
this.age = age;
}
- Hello World
Do's and Dont's
- The purpose of new keyword is to create an object.
- The purpose of a constructor is to initialize an object.
- In the event of creating an object: first new keyword is executed to create an object and then the constructor method of a class is called to initialize the object.
- If you have added a parameterized constructor in your class, then Java won't call the default constructor at all. Java will always call the constructor which you defined in the class.
- If you declare a constructor of a class as private then you have to define a parameterized constructor to create it's object, otherwise you won't be able to create it's object. But you can use it's static methods and properties.
public class Cat {
public static final int NUMBER_OF_MONTHS_IN_A_YEAR = 12;
public final int NUMBER_OF_DAYS_IN_A_WEEK = 7;
public String name;
public void greetUser(String name) {
System.out.println("Hello " + name);
}
private Cat() {
}
public Cat(String name) {
this.name = name;
}
}
Cat chinki = new Cat("Chinki");
chinki.greetUser("Minki");
System.out.println("Hello " + chinki.name);
- Hello World!!!
Comments
Post a Comment