Question 2

(a) Explain method overriding and method overloading with the help of examples.
class H2EA
{
int a,b;
H2EA(int i,int j)
{
a=i;
b=j;
}
void inside()
{
System.out.println("Inside H2EA");
}
int Multiplication()
{
return a*b;
}
}
class H2EB extends H2EA
{
int c;
H2EB(int i,int j,int k)
{
super(i,j);
c=k;
}
void inside()
{
System.out.println("Inside H2EB");
}
int Multiplication(int x)
{
return x*c;
}
}
class methodOverloadingAndOverridingDifferenceH2E
{
public static void main(String args[])
{
H2EB Obj = new H2EB(5,6,7);
Obj.inside(); // Method Overriding
System.out.println("Multiplication = "+Obj.Multiplication()); // Method Overloading
System.out.println("Multiplication = "+Obj.Multiplication(8)); // Method Overloading
}
}
(b) Write a method for computing xy by doing repetitive multiplication. x and y are of type integer and are to be given as command line arguments. Raise and handle exception(s) for invalid values of x and y. Also define method main. Use finally in above program and explain its usage.
class powerExampleInJavaH2E 
{
public static void main(String args[])
{
int x,y,mul;
try
{
x = Integer.parseInt(args[0]);
y = Integer.parseInt(args[1]);
mul = 1;
for(int i=0;i<y;i++)
mul = mul*x;
System.out.println(x+"^"+y+" : " + mul);
}
catch(NumberFormatException e)
{
System.out.println("Exception : "+e);
}
}
}
(b) Explain package and interface by giving examples.
// Package Example


class packageExampleImplementH2E 
{
public static void main(String args[])
{
int x;
help2engg.packageExampleH2E pe = new help2engg.packageExampleH2E();
pe.show();
pe.setMember(15);
x = pe.getMember();
System.out.println("Member of Inside Package : "+x);
}
}
// The file packageExampleH2E.java must be in help2engg folder package help2engg;
public class packageExampleH2E
{
String msg = "Inside Package Of Help2Engg";
int x;
public void show()
{
System.out.println("Message From Inside Package : "+msg);
}
public void setMember(int x)
{
this.x = x;
}
public int getMember()
{
return x;
}
}
//interface Example


interface interfaceClass
{
void interfaceMethod(int p);
}
class interfaceImplement implements interfaceClass
{
public void interfaceMethod(int p1)
{
System.out.println("Interface Class Called with "+p1);
}
public void nonInterfaceMethod(int p1)
{
System.out.println("Interface Implement Class Called with "+p1);
}
}
class interfaceSimpleExampleH2E
{
public static void main(String args[])
{
interfaceImplement IIO = new interfaceImplement();
IIO.interfaceMethod(15);
IIO.nonInterfaceMethod(15);
}
}

Make Comments..!!


Kiran Kulkarni
overloading of function is concept where a function must hold same name but differs in parameters and function overriding is a concept where same function is used more than a times.
Like · Comment ·
Rinkal Patel and Admin like this
Admin
Thanks Kiran for sharing this Information.!
Like · 1 ·
Anamika Rajput
ya kiran and we can also say that overriding only occurs in case of inheritance..
Like · 3 ·
Download Android App