BCA Class and Object
BCA Class and Object
BCA Class and Object
Class
• No-argument Constructor.
• Parameterized Constructor.
1. Default Constructor.
• If there is no constructor in a class, compiler automatically creates a
default constructor.
Cont…
Example
class Student
{
int id;
public static void main(String a[])
{
Student s1=new Student();
System.out.println(s1.id);
}
}
Output: 0
2. No-argument Constructor.
• A constructor that has no parameter is known as no-argument
constructor.
Example
class Bike
{
Bike()
{
System.out.println("Bike is created");
}
public static void main(String a[])
{
Bike b=new Bike();
}
}
Output: Bike is created
3. Parameterized Constructor
• A constructor which has a specific number of parameters is called a
parameterized constructor.
Example
class Student
{
int id;
String name;
Student(int i, String n)
{
id = i;
name = n;
}
void display()
{
System.out.println(id);
System.out.println(name);
}
public static void main(String a[])
{
Student s1 = new Student(111,"Karan");
s1.display();
}
}
Cont…
Output:
111
Karan
Difference between constructor and method in Java
Constructor Method
A Constructor doesn’t have a return type. A Method must have a return type.
Ways to initialize object:
• By reference variable
• By method
• By constructor
1) Initializing an Object by reference variable
• Block
1) Java static variable
• The static variable can be used to refer to the common property of all
objects (which is not unique for each object).
• A static method can be called without the need for creating an instance
(object) of a class.
Restrictions for the static method
• There are two main restrictions for the static method. They are:
• The static method can not use non static data member or call non-static
method directly.
}
}
Cont…
Output:
Static Method
3) Java static block