Method overriding technique in java

 


   

   This is a question on method overriding just focus program outputs and find why?


class Automobile {

        private String drive() {

            return "Driving vehicle";

        }

    }

    

    class Car extends Automobile {

        protected String drive() {

            return "Driving car";

        }

   

    

    }


           

    public class ElectricCar extends Car {

        

  @Override 

public final String drive() 

       { 

      return "Driving electric car"; 

        }

    

        public static void main(String[] args) 

         {

             Car car = new Car();

            System.out.println(car.drive());

            

/*

* Automobile at=new Automobile(); System.out.print(at.drive());

*   // Compilation Error 

*/

            

            

            final Car caru = new ElectricCar();

          System.out.println(caru.drive());

        }

    }



  Program Output 


    Driving car

Driving electric car



  Example 2::


   Let's see if another  source code predicts give

    what will be output?




 class Automobile {

        private String drive() {

            return "Driving vehicle";

        }

    }

    

    class Car extends Automobile {

        protected String drive() {

            return "Driving car";

        }

    }


           

           public class ElectricCar extends Car {

    

        @Override

        public final String drive() {

            return "Driving electric car";

        }

    

        public static void main(String[] wheels) {

            final Car car = new ElectricCar();

            System.out.print(car.drive());// output?

        }

    }


   Program output 

--------------------------

  Compilation  Error   : This   due to the main  method being wrongly defined 





Method overriding technique in java Method overriding  technique in java Reviewed by Mukesh Jha on 11:56 PM Rating: 5

No comments:

Add your comment

All Right Reserved To Mukesh Jha.. Theme images by Jason Morrow. Powered by Blogger.