PJ 4
PJ 4
*imp
Constructors in Java:
=>Constructor is a method having same name of class and executed while object
i
attached with "new" keyword.
thi
=>while declaring constructors we must not use return_type,because the
constructors
ipa
will have Class_return_type.
structure of Constructor:
Ma
sh
Class_name(para_list)
{
ate
//method_body
}
nk
Ve
Ex-program : DemoCon1.java
import java.util.Scanner;
i
thi
class Display
ipa
int x,y;
static Display() Ma
{
System.out.println("****Constructor-Display()*****");
sh
System.out.println("The value x:"+x);
void dis()
nk
{
Ve
System.out.println("****Method-dis()*****");
}
class DemoCon1
i
Display d = new Display();//Con_call
thi
System.out.println("Enter the value of x:");
d.x = s.nextInt();
ipa
System.out.println("Enter the value of y:");
d.y = s.nextInt();
d.dis();//method_call
Ma
d.dis();//method_call
sh
d.dis();//method_call
ate
d.dis();//method_call
nk
}
Ve
o/p:
****Constructor-Display()*****
13
****Method-dis()*****
i
The value y:13
thi
Execution flow of above program:
ipa
ClassFiles:
Display.class
DemoCon1.class(MainClass)
Ma
sh
ate
nk
Ve
===================================================================
=====
faq:
(i)Constructor
(ii)Instance method
i
thi
Object creation.
ipa
method
faq:
sh
define static constructor in Java?
ate
(Compiletion Error)
===================================================================
Ve
===========
faq:
faq:
=>when compiler finds any class without any constructors then compiler will add
i
deafault Constructor.
thi
===================================================================
============
ipa
Ma
sh
ate
nk
Ve