Java Program – how to use constructors in a Java class
Here is a Java program that helps you to understand the concepts of constructors in Java class. This program also tells us how to implement constructors correctly in Java programs to instantiate or create objects or instances.
how to use constructors in a Java class | a Java program showing constructors
class TestConstructor
{
int i,j;
TestConstructor()
{
i=5;
j=6;
}
TestConstructor(int a)
{
i=a;
j=a+1;
}
TestConstructor(int a, int b)
{
i=a;
j=b;
}
void getVal () {
System.out.println(“\nHi from getVal method”);
System.out.println(” i =”+ i);
System.out.println(” j =”+ j);
}
}
class Test3
{
public static void main(String args[])
{
TestConstructor t1= new TestConstructor();
t1.getVal();
TestConstructor t2= new TestConstructor(7);
t2.getVal();
TestConstructor t3= new TestConstructor(9,10);
t3.getVal();
}
}