Constuctors - Java
Constructor is a special member function in object oriented programming because the classname and method name should be same. it has several characterstics
Characterstics
- They will invoke automaticly when an object is created
- They should be in public
- They do not have any return type
- They can't be inherited, though a sub class constructor can call the super class constructor using super keyword
Types of Constructors
- Default Constructors
- Parametarized Constructors
- Overloading Constructors
- Copy Constutors
- Destructors
WRITE A PROGRAM ON CONSTRUCTORS
class Box
{
Box()
{
System.out.println("This is sample");
}
}
class Sample
{
public static void main(String args[])
{
Box k=new Box();
}
}
WRITE A PROGRAM TO FIND THE SUM OF TWO NUMBERS USING PARAMETERIZED CONSTRUCTOR.
class Sum
{
Sum(int x,int y)
{
for(int i=0;i<5;i++)
{
System.out.println(y);
}
}
}
class Sample
{
public static void main(String args[])
{
Sum s=new Sum(10,20);
}
}
WRITE A PROGRAM TO FIND THE AREA OF RECTANGLE AND AREA OF TRIANGLE USING PARAMETERIZED AND OVER LOADING CONSTURCTORS.
class Area
{
Area(int b,int h)
{
System.out.println("Area of rectangle"+(b*h));
}
Area(int x,double y)
{
System.out.println("Area of triangle"+(x*y)/2);
}
Area()
{
int r=10;
System.out.println("Area of circle"+(3.14*r*r));
}
}
class Sample
{
public static void main(String args[])
{
Area a=new Area (10,20);
Area b=new Area (20,30.5);
Area c=new Area ();
}
}
For
More Explanation
&
Online Classes
Contact Us: +919885348743
More Explanation
&
Online Classes
Contact Us: +919885348743