Method Overriding in Java
Let's have a look on below program.
Example
package methodOverriding;
//Class Vehicle
public class Vehicle {
void wheels()
{
System.out.println("Vehicles are of 2 or 4 wheels");
}
}
Class Car
public class Car extends Vehicle {
void wheels()
{
System.out.println("Cars are of 4 wheels");
}
}
//Class Main
public class OverRideDemo {
public static void main(String[] args) {
Vehicle v=new Vehicle();//Vehicle reference and it's object
Vehicle c=new Car();//Vehicle reference but Car object
v.wheels();//method in Vehicle Class
c.wheels();//method in Car class
}
}
//Class Vehicle
public class Vehicle {
void wheels()
{
System.out.println("Vehicles are of 2 or 4 wheels");
}
}
Class Car
public class Car extends Vehicle {
void wheels()
{
System.out.println("Cars are of 4 wheels");
}
}
//Class Main
public class OverRideDemo {
public static void main(String[] args) {
Vehicle v=new Vehicle();
Vehicle c=new Car();
v.wheels();
c.wheels();
}
}
Output
Vehicles are of 2 or 4 wheels
Cars are of 4 wheels
Cars are of 4 wheels
Explanation
To access the method in Super class in subclass ,the super keyword is used.
Example
package methodOverriding;
//Class Vehicle
public class Vehicle {
void wheels()
{
System.out.println("Vehicles are of 2 or 4 wheels");
}
}
Class Car
public class Car extends Vehicle {
void wheels()
{
super.wheels();
System.out.println("Cars are of 4 wheels");
}
}
//Class Main
public class OverRideDemo {
public static void main(String[] args) {
Vehicle c=new Car();//Vehicle reference but Car object
c.wheels();//method in Car class
}
}
//Class Vehicle
public class Vehicle {
void wheels()
{
System.out.println("Vehicles are of 2 or 4 wheels");
}
}
Class Car
public class Car extends Vehicle {
void wheels()
{
super.wheels();
System.out.println("Cars are of 4 wheels");
}
}
//Class Main
public class OverRideDemo {
public static void main(String[] args) {
Vehicle c=new Car();
c.wheels();
}
}
Output
Vehicles are of 2 or 4 wheels
Cars are of 4 wheels
Cars are of 4 wheels
Method Overriding Rules
Method Overriding in Java
Reviewed by LanguageExpert
on
October 01, 2018
Rating:
No comments