What is a constructor in Java?

Java 8Object Oriented ProgrammingProgramming

Constructors are similar to methods but,

  • They do not have any return type.
  • The name of the constructor is same as the name of the class.
  • Every class has a constructor. If we do not explicitly write a constructor for a class, the Java compiler builds a default constructor for that class.
  • Each time a new object is created, at least one constructor will be invoked.
  • A class can have more than one constructor.

Example

public class Puppy {
   public Puppy() {
   }
   public Puppy(String name) {
      // This constructor has one parameter, name.
   }
}
raja
Published on 08-Feb-2018 14:19:05
Advertisements