Advertisement
// Java - Example of method overriding
class A //superclass
{
public void name() //method name() in class A
{
System.out.println("A");
}
}
class B extends A //subclass of A
{
public void name() //method name() of class A is overridden in class B
{
System.out.println("B");
}
}
// Java - Example of method overriding
class Maths
{
int num1, num2;
public int mathOperation(int a, int b) //performing addition operation on two integers.
{
num1=a;
num2=b;
return (num1+num2);
}
}
//Subtract class is inheriting Maths class.
class Subtract extends Maths
{
public int mathOperation(int a, int b) //mathOperation is overridden to perform subtract operation on two integers.
{
num1=a;
num2=b;
return (num1-num2);
}
}
class Override
{
public static void main(String... ar)
{
Subtract ob = new Subtract();
System.out.println(ob.mathOperation(5,2));
}
}
3
Advertisement
// Java - Example of method overriding
class A
{
public A returnObject() //method returnObject() has return type A
{
return new A();
}
}
class B extends A
{
public B returnObject() //overriding method returnObject() has return type B(subtype of A)
{
return new B();
}
}
// Java - Example of method overriding
class A
{
public void showName() //method showName() has "public" access
{
System.out.println("A");
}
}
class B extends A
{
private void showName() //overriding method showName has a more restrictive "private" access
{
System.out.println("B");
}
}
Overriding3.java:11: error: method() in B cannot override method() in A
private void showMethod()
^
attempting to assign weaker access privileges; was public
// Java - Example of method overriding
class A //superclass
{
private void showMethod() //showMethod() has private access and it cannot be overridden.
{
System.out.println("A");
}
}
class B extends A //subclass
{
private void showMethod() //creating a new method showMethod() in class B
{
System.out.println("B");
}
}
class Override
{
public static void main(String... ar)
{
B ob = new B();
ob.showMethod();
}
}
Advertisement
Advertisement
Please check our latest addition
C#, PYTHON and DJANGO
Advertisement