Can we say Constructors are Methods in Java?

后端 未结 4 455
礼貌的吻别
礼貌的吻别 2021-01-29 15:57

As we know Java is an object oriented language. Everything is objects in Java. We also know that objects have something (instance variables / fields) and do something (methods).

4条回答
  •  醉话见心
    2021-01-29 16:27

    Constructor in Java

    Java constructor is invoked at the time of object creation. It constructs the values i.e. provides data for the object that is why it is known as constructor. The constructor actually returns the current class instance (You cannot use return type yet it returns a value). There are basically two rules defined for the constructor.

    1)Constructor name must be same as its class name 2)Constructor must have no explicit return type

    Types of constructors

    1)Default constructor (no-arg constructor)

    class Bike1{  
    Bike1(){System.out.println("Bike is created");}  
    public static void main(String args[]){  
    Bike1 b=new Bike1();  
    }  
    }  
    

    2)Parameterized constructor

    class Student4{  
    int id;  
    String name;  
    
    Student4(int i,String n){  
    id = i;  
    name = n;  
    }  
    void display(){System.out.println(id+" "+name);}  
    
    public static void main(String args[]){  
    Student4 s1 = new Student4(111,"Karan");  
    Student4 s2 = new Student4(222,"Aryan");  
    s1.display();  
    s2.display();  
    

    }
    }

提交回复
热议问题