Constructors in Java

Constructors are special class methods that are used to initialize the object of that class. if u recall the discussion on final variables, you might remember that you had at the time no way to create a book object with an initial title that’s kept as a read-only variable.
1.Constructors with no argument value
2.Constructors with argument value

1.Constructors with no argument value(Default constructor)

syntax:
Public class A 
{ 
MyClass() 
{ 
-
statement;
- 
} 
}

1.Example for without argument constructor(default constructor)

 //Java Program to create and call a default constructor 
class Bike1{ 
//creating a default constructor 
Bike1()
{
System.out.println("Bike is created");
} //main method 
public static void main(String args[])
{ 
//calling a default constructor 
Bike1 b=new Bike1();
 }
 }
Output:
Bike is Created 

2.Constructors with argument value(Parameterized Constructor)

syntax:
class A { 
MyClass(int i )
 { 
-
statement;
-
 }
 }

1.EXAMPLE FOR WITH ARGUMENT CONSTRUCTOR(Parameterized Constructor)

//Java Program to demonstrate the use of the parameterized constructor. 
class Student4
{ 
int id; 
String name; 
//creating a parameterized constructor 
Student4(int i,String n)
{ 
id = i; 
name = n;
 } 
//method to display the values 
void display()
{
System.out.println(id+" "+name);
} 
public static void main(String args[])
{ 
//creating objects and passing values 
Student4 s1 = new Student4(111,"Karan");
 Student4 s2 = new Student4(222,"Aryan");
 //calling method to display the values of object 
s1.display(); 
s2.display();
 }
 } 
Output:
111 Karan
222 Aryan

Translate »