Method Overriding example

Method Overriding example
 package com.ram;

class Car{
 int CC;
 String name;
 
 public void display(){
  System.out.println("Will diaplsy car details ...");
 }
}

class BMW extends Car{
 public void display(){
  name="BMW X5";
  CC = 2979;
  System.out.println(name+" has "+CC+" CC");
 }
}

class Benz extends Car{
 public void display(){
  name = "Mercedes-Benz E class";
  CC = 3498;
  System.out.println(name+" has "+CC+" CC");
 }
}

public class OverrideExample {
 public static void main(String[] args) {
  Car bmw = new BMW();
  Car benz = new Benz();
  
  bmw.display();
  benz.display();
 }
}

 
Execute OverrideExample class and you get the below output:
BMW X5 has 2979 CC
Mercedes-Benz E class has 3498 CC

No comments:

Post a Comment