Constructor Overloading in Java
Constructor
Class name and function name should be same is called function overloading.
It has three types
1. Default constructor
2. Parameterized constructor
3. Multiple constructor
Default constructor
import java.io.*;
class selva
{
public string name;
public int age;
selva() throws IOException
{
DataInputStream in = new DataInputStream(System.in);
{
System.out.println("Enter the name and age is:");
name = in.readLine();
age=Integer.parseInt(in.readLine());
}
}
voidputdata()
{
System.out.println("The given name is:"+name);
System.out.println("The given name is:"+age);
}
}
class arun
{
public Static void main(String args[]) throws IOException
{
selva s=new selva();
s.putdata();
}
}
Parameterized constructor
import java.io.*;
class selva
{
public string name;
public int age;
public int c;
selva(int a,int b) throws IOException
{
DataInputStream in = new DataInputStream(System.in);
{
System.out.println("Enter the name and age is:");
name=in.readLine();
age=Integer.parseInt(in.readLine());
c=a+b;
}
}
void putdata()
{
System.out.println("The given name is :"+name);
System.out.println("The given age is:"+age);
System.out.println("The given value of c is:"+c);
}
}
class arun()
{
public Static void main(String args[]) throws IOException
{
selva s=new selva(100,200);
s.putdata();
}
}
Multiple constructor
import java.io.*;
class selva
{
public string name;
public int age;
public int c;
selva() throws IOException
{
DataInputStream in = new DataInputStream(System.in);
{
System.out.println("Enter the name and age is:");
name=in.readLine();
age=Integer.parseInt(in.readLine());
}
}
selva(int a,int b)
{
c=a+b;
}
void pudata()
{
System.out.println("The given name is:"+name);
System.out.println("The given age is:"+age);
}
void pudata1()
{
System.out.println("The given value of c is :"+c);
}
}
class arun
{
public Static void main(String args[]) throws IOException
{
selva s=new selva();
selva s1=new selva(100,200);
s.putdata();
s1.putdata()1;
}
}
0 Comments