CONSTRUCTOR

Constructor
A constructor in Java is a special method that is used to initialize objects. The constructor is called when an object of a class is created. It can be used to set initial values for object attributes:

constructor program example:
package constructorexcercise;

public class Payticketprice {
int paise;
public Payticketprice() {
paise=100;

}
public static void main(String[] args) {
    Payticketprice payticket=new Payticketprice();// object created here  and constructor called here
    System.out.println("Payticket price "+payticket.paise);
}

}

Result:
Payticket price 100

Note:

  • constructor name match the class name
    *it dosen’t contain return type(like void)
    *All classes have constructors by default: if you do not create a class constructor yourself, Java creates one for you. However, then you are not able to set initial values for object attributes.

Parameters used in constructor example

package constructorexcercise;

public class Buychocolate {
String chocolatename;
int chocolateprice;
public Buychocolate(String name,int price) {
chocolatename=name;
chocolateprice=price;
}
public static void main(String[] args) {
// TODO Auto-generated method stub

System.out.println(“what chocolate you want to buy”);
Buychocolate buy=new Buychocolate(“Dairymilk”,140);
System.out.println(buy.chocolatename+” price is “+ buy.chocolateprice);

}

}

Result:
what chocolate you want to buy
Dairymilk price is 140

Leave a comment

Design a site like this with WordPress.com
Get started