Java Constructors
A constructor in Java is a special member that is called when an object is created. It initializes the new object’s state. It is used to set default or user-defined values for the object's attributes
- A constructor has the same name as the class.
- It does not have a return type, not even void.
- It can accept parameters to initialize object properties.
public class Home
{
//fields
static String homename="Ezhil";
static int homeAge=15;
//non-static variables
String name;
int age;
//constructor
public Home(String name,int age){
this.name=name;
this.age=age;
}
public static void main(String[] args)
{
//object
Home person1=new Home("Anban",30);
Home person2=new Home("Karthikeyan",55);
System.out.println(Home.homename);
System.out.println(Home.homeAge);
System.out.println(person1.name);
System.out.println(person1.age);
System.out.println(person2.name);
System.out.println(person2.age);
}
}
O/P:
Ezhil
15
Anban
30
Karthikeyan
55
public class Supermarket
{
//fields
static String supermarketname="D-Mart";
static int supermarketdoorno=13/1;
//non-static variables
String things;
int price;
int discount;
public Supermarket(String things,int price){
this.things=things;
this.price=price;
}
public Supermarket(String things,int price,int discount){
this.things=things;
this.price=price;
this.discount=discount;
}
public static void main(String[] args)
{
//object
Supermarket things1=new Supermarket("Rosemilk",30);
Supermarket things2=new Supermarket("Galaxychocky",50);
Supermarket things3=new Supermarket("Kinderjoy",50,20);
System.out.println(Supermarket.supermarketname);
System.out.println(Supermarket.supermarketdoorno);
System.out.println(things1.things);
System.out.println("₹" + things1.price);
System.out.println(things2.things);
System.out.println("₹" + things2.price);
System.out.println(things3.things);
System.out.println("₹" + things3.price);
System.out.println(things3.discount + "%" );
}
}
0/P:
D-Mart
13
Rosemilk
₹30
Galaxychocky
₹50
Kinderjoy
₹50
20%
Reference
https://www.geeksforgeeks.org/java/constructors-in-java/
Top comments (0)