Apply for Zend Framework Certification Training

Java



< Looping Through Array Elements in Java Method Overriding in Java – Short Notes >



A constructor in Java is a special method used to initialize an object when it is created.

Key Points
Constructor name must be same as the class name.
It has no return type, not even void.
It is called automatically when an object is created.
Constructors are mainly used to initialize variables.
A class can have multiple constructors (constructor overloading).

Example
public class java_constructor {
    private String name;
    public java_constructor() {
        System.out.println("Constructor called :");
        name="webphplearn.com";

    }
    
    public static void main(String[] args) {
        java_constructor jc = new java_constructor();
        System.out.println("The name is :"+ jc.name);

    }
}

Types of Constructors
Default Constructor – Provided by Java if no constructor is written.
No-Argument Constructor – A constructor with no parameters.
Parameterized Constructor – A constructor that accepts parameters.

Example

public class java_constructor_paramaterized {
    String language;
    java_constructor_paramaterized(String lang) {
        language = lang;
        System.out.println(language+" Programming language");

    }
    public static void main(String[] args) {
        java_constructor_paramaterized jcp =new java_constructor_paramaterized("Java");
    }

    
}

Constructor overloading means having more than one constructor in the same class, with different parameter lists.
It is an example of compile-time polymorphism.

Key Points
A class can have multiple constructors.
Constructors must have the same name as the class.
Each constructor must have a different parameter list.
Constructors can differ by:
Number of parameters
Type of parameters
Order of parameters
Return type is not used to overload constructors.

 

Example
public class java_constructor_overloading {
    String language;
    java_constructor_overloading(){
        this.language = "Java is a language";
    }

    java_constructor_overloading(String language){
        this.language = language;
    }
    public void getName(){
        System.out.println("Your programming language is :"+ this.language);
    }

    public static void main(String[] args) {
        java_constructor_overloading  JCO1 = new java_constructor_overloading();
        java_constructor_overloading  JCO2 = new java_constructor_overloading("Python");
        JCO1.getName();
        JCO2.getName();
    }
}

< Looping Through Array Elements in Java Method Overriding in Java – Short Notes >



Ask a question



  • Question:
    {{questionlistdata.blog_question_description}}
    • Answer:
      {{answer.blog_answer_description  }}
    Replay to Question


Back to Top