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:
![Method Overriding in Java](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiU6NHGDlPSaz5wX0O5fOS6bEhCAsDThBvBA9lkNz47Fp6_I5xFSYDzdgpNcSxwSGabFyVsda2aQ7D8iZqvd9Dg087QfZUpQ6uzWUZTYuAx5fYmuMiVAo-ERWYq9FCjPpU_QFC711l9eMh-/s72-c/Method+Overriding+in+Java.jpg)
No comments