Overloading and Overriding Examples
Example to show method overloading
Example to show method overriding
Example to show method overloading
class Calculator
{
public void add(int x,int y)
{
System.out.println(x+y);
}
public void add(int x,int y, int z)
{
System.out.println(x+y+z);
}
public void add(float x,float y)
{
System.out.println(x+y);
}
public int add(long x,long y)
{
return (x+y);
}
public static void main(String args[])
{
Calculator obj=new Calculator();
obj.add(10,20);
obj.add(10,20,30);
obj,add(10.1f,20.2f);
obj.add(10l,20l);
}
}
Output
30 60 30.300001 30
Example to show method overriding
Example to show method overriding
class person
{
int age;
String name;
String address;
void input()
{
age=21;
name="ram";
address="delhi";
}
void print()
{
System.out.println("name = "+name);
System.out.println("age = "+age);
System.out.println("address = "+address);
}
}
class Emp extends person
{
int empno;
int deptno;
void input()
{
super.input();
empno=01;
deptno=101;
}
void print()
{
super.print();
System.out.println("employ no = "+empno);
System.out.println("dept no. = "+deptno);
}
}
class Customer extends person
{
int custId;
int custno;
void input()
{
//super.input();
name="smith";
age=100;
address="mumbai";
custno=02;
custId=1001;
}
void print()
{
super.print();
System.out.println("custno = "+custno);
System.out.println("custId = "+custId);
}
}
public class TestOverriding
{
public static void main(String s1[])
{
Emp emp=new Emp();
emp.input();
emp.print();
Customer customer=new Customer();
customer.input();
customer.print();
}
}
Output
name = ram age = 21 address = delhi employ no = 1 dept no. = 101 name = smith age = 100 address = mumbai custno = 2 custId = 1001


