-3
  1. As if you extend the class and override the method then what will be the difference between new method and overridden method, except same name and method signature .

  2. In the below code class A has some method parentMethod() and the same is overridden in class B by extending class A.

I want to know what is the difference between overridden method and a new method except the name and why we need to go for overridden method with classes.

class A {
    void parentMethod(){
       //some code
    }
}

class B extends A {
    void parentMethod() { //overridden method
        //some overridden code
    }
    void childMethod() {//new method
        //some new code
    }
}
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
sanju
  • 11
  • 6

2 Answers2

0

Overriding is used when you have two classes with very similar code. Some of the code is different so you want to have some common code and some abstract methods that can be changed from variation to variation. The variations will turn into abstract classes that extend your base class. Read more here https://docs.oracle.com/javase/tutorial/java/IandI/abstract.html.

NickDim
  • 17
  • 3
  • The method doesn't have to be abstract to be overridden. But yeah, true, but not a complete answer. – Norbert Bicsi Nov 21 '17 at 19:20
  • I have gone through many answers and articles but this is what i found is, – sanju Nov 29 '17 at 09:45
  • is,Overridden method we can use only when we are having similar method name and signature to just simplify the code by providing it readability it will help in remembering the method name and ease to use. – sanju Nov 29 '17 at 09:54
0

Override method use with example is explained below.

You can use it where you want to use the same "method name" and "signature" but need to give new code functionality.

Check the below code where,

1. class "Car" is there.
2. created default method for car as "myHorn()".
3. created new class as "Ferrari".
4. overriden the method "myHorn(), as for car i want to use new horn.
5. now for all cars you can create override the "myHorn()" method and customize code.

Class Car{
//parent class method having default horn
void myHorn(){
System.out.println("peeee..peeeee.peee");
}
}

class Ferrari extends Car{
//overridden method using same method and overriding horn
void myHorn(){
System.out.println("fuuuuuuuuuuu..fuuuuuuuuuu");
}
}

class Swift extends Car{
//Creating object of Swift class and calling  method of Class "'Car"
Swift car = new Swift();
//if want to use default horn
car.myHorn();
}
}
sanju
  • 11
  • 6
  • The Swift car isn't overriding anything – OneCricketeer Nov 29 '17 at 13:49
  • For Swift car I want to use default horn which is in "Car" class method "myHorn" so I am accessing that by calling it instead of overriding, I just mentioned object wrongly it has to be Swift Swift =new Swift(); // as I can access the object by child class as it is already extending Car – sanju Nov 30 '17 at 14:23