CONSTRUCTOR :A
Constructor is a set of instructions designed to initialize an instance of a
newly created object.
Two Rules defined for the Constructors :
1. Default Constructor:
· Parameterized constructors are required to pass parameters on creation of objects.
METHOD :
public void add (int a, int b) { }
A Java method is a collection of statements that are grouped together to perform an operation. access return type name parameters Body
Example
programs of Constructors :
1)
Default Constructor
:
package
org.javanoobs.dconstructor;
public class DefaultConstructor {
// This is the
Constructor
public DefaultConstructor()
{
System.out.println(" I am inside
the default constructor !!! ");
}
public static void main(String args[])
{
// Object created..
DefaultConstructor
dCon = new DefaultConstructor();
}
}
OUTPUT
:
I am
inside the default constructor !!!
2) Parameterized Constructor :
package
org.javanoobs.pconstructor;
public class Test2 {
int a, b; // instance
variables.
static int c;
// this is the
instance block.
{
System.out.println(" Inside
Instance Block ");
System.out.println(" C = " + c);
System.out.println(" A = " + a);
}
static {
System.out.println("Inside the
static block !!!");
System.out.println(" C = " + c);
}
public void disp() {
int d = 1; // Local varables,
initialize to 0 or 1 or will result in an
// error.
d
+= a + b + c;
System.out.println("d after
addition : " + d);
System.out.println(" Disp method
called...");
}
public static void main(String args[])
{
Test2
t; // refference
variable .
t
= new Test2(); // t is the object
.
t.disp();
}
}
package
org.javanoobs.pconstructor;
public class
ParameterizedConstructor {
private String name;
public
ParameterizedConstructor(String str) {
this.name = str;
System.out.println("I am Inside
Parametrized Constructor !!!");
System.out.println("The parameter
Value is : " + str);
}
public static void main(String args[])
{
ParameterizedConstructor
pCon = new ParameterizedConstructor(" Java Noobs !!! ");
}
}
OUTPUT
:
I am Inside Parametrized Constructor
!!!
The parameter Value is : Java Noobs !!!
This comment has been removed by the author.
ReplyDelete