Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 16
Java
Constructors What is a Constructor?
• A constructor in Java is similar to a method that is invoked
when an object of the class is created. • Unlike Java methods, a constructor has the same name as that of the class and does not have any return type. For example, Types of Constructor
• In Java, constructors can be divided into 3 types:
• No-Arg Constructor • Parameterized Constructor • Default Constructor • 1. Java No-Arg Constructors • Similar to methods, a Java constructor may or may not have any parameters (arguments). • If a constructor does not accept any parameters, it is known as a no-argument constructor. For example, 2. Java Parameterized Constructor
• A Java constructor can also accept one or more
parameters. Such constructors are known as parameterized constructors (constructor with parameters). 3. Java Default Constructor
• If we do not create any constructor, the Java compiler
automatically create a no-arg constructor during the execution of the program. This constructor is called default constructor. • Here, we haven't created any constructors. Hence, the Java compiler automatically creates the default constructor. • The default constructor initializes any uninitialized instance variables with default values. Important Notes on Java Constructors
• Constructors are invoked implicitly when you instantiate objects.
• The two rules for creating a constructor are: • The name of the constructor should be the same as the class. • A Java constructor must not have a return type. • If a class doesn't have a constructor, the Java compiler automatically creates a default constructor during run- time. The default constructor initializes instance variables with default values. For example, the int variable will be initialized to 0 • Constructor types: • No-Arg Constructor - a constructor that does not accept any arguments • Parameterized constructor - a constructor that accepts arguments • Default Constructor - a constructor that is automatically created by the Java compiler if it is not explicitly defined. • A constructor cannot be abstract or static or final. • A constructor can be overloaded but can not be overridden. Constructors Overloading in Java
• Similar to Java method overloading, we can also create two
or more constructors with different parameters. This is called constructors overloading. • we have two constructors: Main() and Main(String language). Here, both the constructor initialize the value of the variable language with different values.
• Based on the parameter passed during object creation,
different constructors are called and different values are assigned. Thank you