DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

  1. DZone
  2. Coding
  3. Java
  4. All About Overriding in Java

All About Overriding in Java

If you want to ensure you're overriding the right way, take a look at this guide, which dives into the various means at your disposal and some pitfalls to watch out for.

By 
Madhusudana Singana user avatar
Madhusudana Singana
·
Apr. 11, 17 · Tutorial
Likes (13)
Comment (0)

Save
Tweet
Share
47.93K Views

Join the DZone community and get the full member experience.

Join For Free

A child class can redefine the instance methods of its parent class. This is called method overriding. The signature (return type, parameter type, the number of parameters, and order of parameters) must be the same as defined in the parent class. Method overriding is done to achieve runtime polymorphism.

What Is Polymorphism?

Polymorphism allows you define one interface and have multiple implementations. This is one of the basic principles of object-oriented programming. The word ‘polymorphism’ literally means ‘a state of having many shapes’ or ‘the capacity to take on different forms.’ When applied to object-oriented programming languages like Java, it describes a language’s ability to process objects of various types and classes through a single, uniform interface.

What Is Runtime Polymorphism (or Dynamic Method Dispatch?)

An overridden method is called according to the object invoking it, not according to the reference type.

What Is the Use of Runtime Polymorphism?

Static vs. Dynamic Polymorphism?

Private, final, and static methods and variables use static bindings and are bonded by compiler while virtual methods are bonded during runtime based on the runtime object.

@Override Usage

Use @Override so that you can take advantage of the compiler to make sure you actually are overriding a method when you think you are. This way, if you make a common mistake like misspelling a method name or not correctly matching the parameters, you will be warned that your method does not actually override like you think it does. Secondly, it makes your code easier to understand because it is more obvious when methods are overwritten.

Additionally, in Java 1.6, you can use it to mark when a method implements an interface for the same benefits.

Rules for Dynamic Polymorphism

Change in Method Signature

If we use overriding, then the overriding method should have the same signature as the overridden method. You can change the method signature accordingly in your child class, i.e number of arguments, type and order of arguments, and return type. But this is known as overloading.

​x
1
package com.me.overriding;
2
​
3
​
4
class Parent_params {
5
    void method(String a, String b, int v, float d) {
6
        System.out.println("parent");
7
    }
8
​
9
    void method2(String a, String b, int v) {
10
        System.out.println("parent");
11
    }
12
​
13
    void method3(String a, int v) {
14
        System.out.println("parent");
15
    }
16
}
17
​
18
class Child_Params extends Parent_params {
19
    //If we want to override the parent class you need to have same
20
    //no of params as parent had
21
    //WRONG...
22
    /*@Override
23
    void method(String a){
24
    System.out.println("child");
25
    }*/
26
​
27
    //Order of the params should also be same as parent
28
    //WRONG
29
    /*@Override
30
    void method(String a,float d,int a,String b){
31
    System.out.println("parent");
32
    }*/
33
​
34
    //Override
35
    @Override
36
    void method(String a, String b, int v, float d) {
37
        System.out.println("child");
38
    }
39
​
40
    //Overloading
41
    //We can define a method like this
42
    void method(String a, String b, int v) {
43
        System.out.println("child");
44
    }
45
​
46
    void method2(String a, int b, String v) {
47
        System.out.println("child");
48
    }
49
​
50
    void method3(int v, String a) {
51
        System.out.println("child");
52
    }
53
​
54
}
55
public class Override_Params {
56
    public static void main(String[] args) {
57
        String temp = "Monday";
58
        Child_Params child_Params = new Child_Params();
59
​
60
​
61
        /*Parent_params params=new Child_Params();
62
        child_Params=(Child_Params) params;
63
        child_Params.method(temp,temp,2);*/
64
​
65
        Parent_params params2 = new Parent_params();
66
        child_Params = (Child_Params) params2;
67
        child_Params.method(temp, temp, 2);
68
​
69
​
70
        /*up vote
71
        3
72
        down vote
73
        accepted
74
        Once you create an object, you can't change its type. 
75
        That's why you can't cast an Animal to a Dog.
76
​
77
        However, if you create an object of a sub-class, 
78
        you can keep a reference to it in a variable of the super-class type, 
79
        and later you can cast it to the sub-class type.
80
​
81
        This will work :
82
​
83
        Animal a = new Dog ();
84
        Dog d = (Dog) a;*/
85
    }
86
}
87
​


Return Type of the Method

Return types may vary among methods that override each other if the return types are reference types. The notion of return-type-substitutability supports covariant returns — the specialization of the return type to a subtype. A method declaration d1 with return type R1 is return-type-substitutable for another method d2 with return type R2 if and only if the following conditions hold:

If R1 is void then R2 is void.

If R1 is a primitive type, then R2 is identical to R1.

If R1 is a reference type then: R1 is either a subtype of R2 or R1 can be converted to a subtype of R2 by unchecked conversion (§5.1.9), or

R1 = |R2|

28
1
package com.me.overriding;
2
​
3
class Parent1 {
4
    public void method(String string) {
5
        System.out.println("Parent   :" + string);
6
    }
7
​
8
    public void method2(String string) {
9
        System.out.println("Parent   :" + string);
10
    }
11
}
12
​
13
class Child1 extends Parent1 {
14
​
15
    //The return type is incompatible with Parent1.method(String)
16
​
17
    @Override
18
    public int method(String string) {
19
        System.out.println("Child   :" + string);
20
    }
21
}
22
public class OverrideAllMethods {
23
    public static void main(String[] args) {
24
        Child1 child1 = new Child1();
25
        child1.method("Me");
26
    }
27
}
28
​


Co-Variant Return Type

A covariant return means that when one overrides a method, the return type of the overriding method is allowed to be a subtype of the overridden method's return type.

To clarify this with an example, a common case is Object.clone(), which is declared to return a type of Object. You could override this in your own class as follows:

46
1
package com.me.overriding;
2
​
3
​
4
class ParentCustomClass {
5
    public Object m1() {
6
        System.out.println(" parent m1()");
7
        return null;
8
    }
9
​
10
    public ParentCustomClass m2() {
11
        System.out.println(" parent m2()");
12
        return null;
13
    }
14
}
15
​
16
class ChildtCustomClass extends ParentCustomClass {
17
    @Override
18
    public String m1() {
19
        System.out.println("child m1()");
20
        return null;
21
    }
22
​
23
    @Override
24
    public ChildtCustomClass m2() {
25
        System.out.println(" child m2()");
26
        return null;
27
    }
28
}
29
​
30
public class CoVarientTypes {
31
    public static void main(String[] args) {
32
        ParentCustomClass class1 = new ChildtCustomClass();
33
        class1.m1();
34
        class1.m2();
35
​
36
​
37
        /*A method declaration d1 with return type R1 is return-type-substitutable for another method d2 with return type R2, if and only if the following conditions hold:
38
​
39
        If R1 is void then R2 is void.
40
        If R1 is a primitive type, then R2 is identical to R1.
41
        If R1 is a reference type then:
42
        R1 is either a subtype of R2 or R1 can be converted to a subtype of R2 by unchecked conversion (§5.1.9), or
43
        R1 = |R2|*/
44
​
45
    }
46
}


Static Method Overriding (or) Method Binding

35
1
package com.me.overriding;
2
​
3
class ParentStatic {
4
    public static void method(String string) {
5
        System.out.println("Parent   :" + string);
6
    }
7
​
8
    public void method2(String string) {
9
        System.out.println("Parent   :" + string);
10
    }
11
}
12
​
13
class ChildStatic extends ParentStatic {
14
​
15
    public static void method(String string) {
16
        System.out.println("Child   :" + string);
17
    }
18
}
19
public class StaticMethodOverriding {
20
    public static void main(String[] args) {
21
​
22
        /*1) For class (or static) methods, the method according to the type of 
23
        reference is called, not according to the abject being referred, which means 
24
        method call is decided at compile time.
25
​
26
        2) For instance (or non-static) methods, the method is called according to the type 
27
        of object being referred, not according to the type of reference, which means method 
28
        calls is decided at run time.*/
29
​
30
        ChildStatic.method("Me");
31
​
32
        ParentStatic parentStatic = new ChildStatic();
33
        parentStatic.method("Me");
34
    }
35
}


Static Variable Binding

29
1
package com.me.overriding;
2
​
3
class Dad {
4
    private static final String me = "dad";
5
​
6
    protected String getMe() {
7
        return me;
8
    }
9
​
10
    public void printMe() {
11
        System.out.println(getMe());
12
    }
13
}
14
​
15
class Son extends Dad {
16
    private static final String me = "son";
17
​
18
    @Override
19
    protected String getMe() {
20
        return me;
21
    }
22
}
23
​
24
class StaticVariableOverriding {
25
    public static void main(String[] args) {
26
        Dad dad = new Son();
27
        dad.printMe();
28
    }
29
}


Final and Private Methods

32
1
package com.me.overriding;
2
class Parent_2 {
3
    public final void m1() {
4
        System.out.println("m1()");
5
    }
6
​
7
    private void m2() {
8
        System.out.println("m2() parent");
9
    }
10
}
11
​
12
//Cannot override the final method from Parent_2
13
class Child_2 extends Parent_2 {
14
    public fianl void m1() {
15
        System.out.println("m1()");
16
    }
17
​
18
    private void m2() {
19
        System.out.println("m2() of child");
20
    }
21
}
22
​
23
​
24
public class FinalandprivateOverriden {
25
    public static void main(String[] args) {
26
        Parent_2 child_2 = new Child_2();
27
        child_2.m1();
28
​
29
        //The method m2() from the type Parent_2 is not visible
30
        child_2.m2();
31
    }
32
}


Override Access Levels

22
1
package com.me.overriding;
2
class Parent_Access {
3
    protected void method(String a, String b, int v, float d) {
4
        System.out.println("parent");
5
    }
6
}
7
​
8
class Child_Access extends Parent_Access {
9
    //Access levels cannot be restrictive
10
    /*private void method(String a,String b,int v,float d){
11
    System.out.println("parent");
12
    }*/
13
​
14
    public void method(String a, String b, int v, float d) {
15
        System.out.println("parent");
16
    }
17
}
18
public class Override_AccessLevels {
19
    public static void main(String[] args) {
20
​
21
    }
22
}


Override With super() 

40
1
package com.me.overriding;
2
​
3
class SuperParent {
4
    public void m1() {
5
        System.out.println(" super m1()");
6
    }
7
​
8
    protected void m2() {
9
        System.out.println(" super m2()");
10
    }
11
​
12
    private void m3() {
13
        System.out.println(" super m3()");
14
    }
15
}
16
​
17
class SuperChild extends SuperParent {
18
    public void m1() {
19
        super.m1();
20
        super.m2();
21
        System.out.println("m1()");
22
    }
23
​
24
    protected void m2() {
25
        System.out.println("m2()");
26
    }
27
​
28
    private void m3() {
29
        System.out.println(" m3()");
30
    }
31
}
32
​
33
public class OverridingWithSuper {
34
    public static void main(String[] args) {
35
        SuperParent parent = new SuperChild();
36
        parent.m1();
37
        parent.m2();
38
​
39
    }
40
}


Override With Abstraction

55
1
package com.me.overriding;
2
​
3
interface Interface {
4
    public void m1();
5
}
6
​
7
​
8
/*If an abstract class implements the above interface,
9
then it doesn’t require the subclass to override the move() method, 
10
as shown in the following AbstractDog class:*/
11
​
12
​
13
abstract class AbstractClass implements Interface {
14
    public abstract void m2();
15
    public void m3() {
16
        System.out.println("m3()");
17
    }
18
}
19
​
20
​
21
/*//But if a concrete (non-abstract) class, says BullDog, is a subclass of the 
22
AbstractDog class or the Animal interface, then it must override all the inherited 
23
abstract methods, as shown below:*/
24
​
25
​
26
class ConcreteClass extends AbstractClass {
27
​
28
    @Override
29
    public void m1() {
30
        // TODO Auto-generated method stub
31
        System.out.println("m1()");
32
    }
33
​
34
    @Override
35
    public void m2() {
36
        // TODO Auto-generated method stub
37
        System.out.println("m2()");
38
    }
39
​
40
    @Override
41
    public void m3() {
42
        // TODO Auto-generated method stub
43
        System.out.println("m3()");
44
    }
45
​
46
}
47
​
48
public class OverridingWithAbstraction {
49
    public static void main(String[] args) {
50
        ConcreteClass class1 = new ConcreteClass();
51
        class1.m1();
52
        class1.m2();
53
        class1.m3();
54
    }
55
}


Override With Exceptions

52
1
package com.me.overriding;
2
​
3
import java.io.IOException;
4
import java.nio.file.DirectoryIteratorException;
5
​
6
class ExceptionParent {
7
    public void m1() throws IOException {
8
        System.out.println("m1()");
9
    }
10
}
11
​
12
//Exception Exception is not compatible with throws clause in ExceptionParent.m1()
13
//It should be sam or narrowed or unchecked exception
14
​
15
//CE
16
/*class ExceptionChild extends ExceptionParent{
17
public void m1() throws Exception{
18
System.out.println("m1()");
19
}*/
20
​
21
//CE
22
//IllegalArgumentException is Un-checked 
23
/*class ExceptionChild extends ExceptionParent{
24
public void m1() throws Exception,IllegalArgumentException{
25
System.out.println("m1()");
26
}*/
27
​
28
//OK bccz of Un-Checked Exception
29
/*class ExceptionChild extends ExceptionParent{
30
public void m1() throws IllegalArgumentException{
31
System.out.println("m1()");
32
}*/
33
​
34
/*//CE bcz of Checked
35
class ExceptionChild extends ExceptionParent{
36
public void m1() throws IOException,InterruptedException{
37
System.out.println("m1()");
38
}*/
39
​
40
class ExceptionChild extends ExceptionParent {
41
    public void m1() throws IOException {
42
        System.out.println("m1()");
43
    }
44
​
45
}
46
​
47
public class OverridingExceptions {
48
    public static void main(String[] args) throws IOException {
49
        ExceptionParent exceptionParent = new ExceptionChild();
50
        exceptionParent.m1();
51
    }
52
}


Overriding From Inner Private Classes

33
1
package com.me.overriding;
2
​
3
/* Java program to demonstrate whether we can override private method 
4
of outer class inside its inner class */
5
public class OverrideprivateInnerclass {
6
    private String msg = "GeeksforGeeks";
7
    private void fun() {
8
        System.out.println("Outer fun()");
9
    }
10
​
11
    class Inner extends OverrideprivateInnerclass {
12
        private void fun() {
13
            System.out.println("Accessing Private Member of Outer: " + msg);
14
        }
15
    }
16
​
17
    public static void main(String args[]) {
18
​
19
        // In order to create instance of Inner class, we need an Outer 
20
        // class instance. So, first create Outer class instance and then
21
        // inner class instance.
22
        OverrideprivateInnerclass o = new OverrideprivateInnerclass();
23
        Inner i = o.new Inner();
24
​
25
        // This will call Inner's fun, the purpose of this call is to 
26
        // show that private members of Outer can be accessed in Inner.
27
        i.fun();
28
​
29
        // o.fun() calls Outer's fun (No run-time polymorphism).
30
        o = i;
31
        o.fun();
32
    }
33
}


Overriding and Overloading

32
1
package com.me.overriding;
2
​
3
class ParentStatic_1 {
4
    public void method(String string) {
5
        System.out.println("Parent   :" + string);
6
    }
7
​
8
    public void method2(String string) {
9
        System.out.println("Parent   :" + string);
10
    }
11
}
12
​
13
class ChildStatic_1 extends ParentStatic_1 {
14
​
15
    public static void method(String string, int b) {
16
        System.out.println("Child   :" + string);
17
    }
18
​
19
    public static void method2(String string, int b, float c) {
20
        System.out.println("Child   :" + string);
21
    }
22
}
23
public class OverrideAndOverloadMethods {
24
    public static void main(String[] args) {
25
​
26
        //In a subclass (or Derived Class), we can overload the methods inherited from the
27
        //superclass. Such overloaded methods neither hide nor override the superclass methods — they are new methods, unique to the subclass.
28
​
29
        ParentStatic_1 parentStatic = new ChildStatic_1();
30
        parentStatic.method("Me");
31
    }
32
}


Multi-Level Override

40
1
package com.me.overriding;
2
class ParentStatic_2 {
3
    public void method(String string) {
4
        System.out.println("Parent   :" + string);
5
    }
6
​
7
    public void method2(String string) {
8
        System.out.println("Parent   :" + string);
9
    }
10
}
11
​
12
class ChildStatic_2 extends ParentStatic_2 {
13
​
14
    public void method(String string) {
15
        System.out.println("Child  -1 :" + string);
16
    }
17
}
18
​
19
class ChildStatic_3 extends ChildStatic_2 {
20
​
21
    public void method(String string) {
22
        System.out.println("Child -2  :" + string);
23
    }
24
}
25
​
26
class ChildStatic_4 extends ChildStatic_3 {
27
​
28
    public void method(String string) {
29
        System.out.println("Child -3  :" + string);
30
    }
31
}
32
​
33
public class MultilevelOverriding {
34
    public static void main(String[] args) {
35
​
36
        //We no need to overwrite all the methods that are there in super class.
37
        ParentStatic_2 parentStatic_2 = new ChildStatic_3();
38
        parentStatic_2.method("hey........!");
39
    }
40
}


Instance vs Static Method Override

35
1
package com.me.overriding;
2
​
3
​
4
class ParentStatic2 {
5
    public static void method(String string) {
6
        System.out.println("Parent   :" + string);
7
    }
8
​
9
    public void method2(String string) {
10
        System.out.println("Parent   :" + string);
11
    }
12
}
13
​
14
class ChildStatic2 extends ParentStatic {
15
​
16
    //This static method cannot hide the instance method from ParentStatic
17
    public void method(String string) {
18
        System.out.println("Child   :" + string);
19
    }
20
​
21
    //This static method cannot hide the instance method from ParentStatic
22
    public static void method2(String string) {
23
        System.out.println("Child   :" + string);
24
    }
25
}
26
public class InstanceVsStaticOverriding {
27
    public static void main(String[] args) {
28
​
29
        //An instance method cannot override a static method, 
30
        //and a static method cannot hide an instance method. 
31
​
32
        ParentStatic2 parentStatic = new ChildStatic2();
33
        parentStatic.method("Me");
34
    }
35
}


Instance vs. Static Variable Override

42
1
package com.me.overriding;
2
​
3
class B
4
{
5
     int a=10;
6
     public void print()
7
     {
8
         System.out.println("inside B super class");
9
     }
10
​
11
}
12
 class C extends B
13
 {
14
     int a=20;
15
     public void print()
16
     {
17
         System.out.println("inside C sub class");
18
     }
19
​
20
​
21
 }
22
public class InstanceVariableOverriding  {
23
    public static void main(String[] args) {
24
        B b=new C();
25
        b.print();//it will print inside c sub class
26
        System.out.println(b.a);//it will print super class variable value=10
27
​
28
      /*  
29
        Why instance variable of super class is not overridden in sub class method see my code below ...
30
        Because instance variables CANNOT be overridden in Java. In Java only methods can be overridden.
31
​
32
        When you declare a field with the same name as an existing field in a
33
        superclass, the new field hides the existing field. The existing field from 
34
        the superclass is still present in the subclass, and can even be used ... 
35
​
36
        subject to the normal Java access rules.*/
37
​
38
​
39
    }
40
​
41
}
42
​


Constructor Override

40
1
package com.me.overriding;
2
​
3
class One {
4
    public One() { // Super Class constructor
5
​
6
    }
7
​
8
    One(int a) { // Super Class Constructor Overloading
9
​
10
    }
11
}
12
​
13
class Two extends One {
14
    /* {
15
      //One() {    // this is a method not constructor 
16
         // because name should not match with Class name
17
     }*/
18
​
19
    Two() { // sub class constructor
20
    }
21
​
22
    Two(int b) { // sub class constructor overloading
23
​
24
    }
25
}
26
public class ConstructorOverriding {
27
​
28
​
29
    /*It is never possible. Constructor Overriding is never possible in Java.
30
​
31
    This is because,
32
​
33
    Constructor looks like a method but name should be as class name and no return value.
34
​
35
    Overriding means what we have declared in Super class, that exactly we have to declare in Sub class it is called Overriding. Super class name and Sub class names are different.
36
​
37
    If you try to write Super class Constructor in Sub class, then Sub class will treat that a*/
38
    //s a method not constructor because name should not match with Sub class name. And it will give an compilation error that methods does not have return value. So we should declare as void, then only it will compile.
39
​
40
}


Constructor With super()

23
1
package com.me.overriding;
2
​
3
class Superclass {
4
    public Superclass(int x) {
5
        System.out.println("000000");
6
    }
7
​
8
    public Superclass() {
9
        System.out.println("  ty");
10
    }
11
    public Superclass(String y) {}
12
}
13
​
14
class Subclass extends Superclass {
15
    public Subclass() {
16
        // super(5); // chain to Superclass(int) constructor
17
    }
18
}
19
public class ConstructorWithSuper {
20
    public static void main(String[] args) {
21
        new Subclass();
22
    }
23
}


Other Package and Same Package Override

76
1
package com.me.overridingtest;
2
​
3
import com.me.overriding.PackageParent;
4
​
5
public class Child extends PackageParent {
6
​
7
    @Override
8
    public void m1() {
9
        System.out.println("m1()");
10
    }
11
​
12
    @Override
13
    protected void m2() {
14
        System.out.println("m2()");
15
    }
16
​
17
    //Defalut methods are allowed only ininterface
18
    /*default void m3(){
19
    System.out.println("m3()");
20
    }*/
21
​
22
    //A subclass in a different package can only override the non-final 
23
    //methods declared public or protected.
24
​
25
    @Override
26
    private void m4() {
27
        System.out.println("m1()");
28
    }
29
}
30
​
31
​
32
package com.me.overriding;
33
​
34
import com.me.overridingtest.Parent;
35
​
36
public class OtherPackageOverride {
37
    public static void main(String[] args) {
38
        Parent parent = new com.me.overridingtest.Child();
39
        parent.m1();
40
        parent.m2();
41
    }
42
}
43
​
44
​
45
package com.me.overriding;
46
​
47
public class PackageParent {
48
    public void m1() {
49
        System.out.println("m1()");
50
    }
51
    protected void m2() {
52
        System.out.println("m2()");
53
    }
54
​
55
    //Defalut methods are allowed only ininterface
56
    /*default void m3(){
57
    System.out.println("m3()");
58
    }*/
59
​
60
​
61
    private void m4() {
62
        System.out.println("m1()");
63
    }
64
}
65
​
66
|
67
Class | Package | Subclass | Subclass | World |
68
    | | (same pkg) | (diff pkg) | ————————————+——————— +————————— +—————————— +—————————— +————————
69
    public | + | + | + | + | +———————————— +——————— +————————— +—————————— +—————————— +————————
70
    protected | + | + | + | + | o———————————— + ——————— +————————— +—————————— +—————————— +————————
71
    no modifier | + | + | + | o | o———————————— + ——————— +————————— +—————————— +—————————— +————————
72
    private | + | o | o | o | o
73
​
74
    +
75
    : accessible
76
o: not accessible


Child-Parent Rules: Consequences With Overriding

75
1
//Child Parents Rules While IS-A relationship:
2
​
3
package com.me.overriding;
4
class Parent {
5
    public void method(String string) {
6
        System.out.println("Parent   :" + string);
7
    }
8
​
9
    public void method2(String string) {
10
        System.out.println("Parent   :" + string);
11
    }
12
}
13
​
14
class Child extends Parent {
15
    @Override
16
    public void method(String string) {
17
        System.out.println("Child   :" + string);
18
    }
19
}
20
public class ChildParenRule {
21
    public static void main(String[] args) {
22
        //All well it will print
23
        // Parent   :Me
24
​
25
        //Parent parent=new Parent();
26
        //parent.method("Me");
27
​
28
​
29
        //If we comment method in Parent and remove override in child
30
        //It throws CE
31
        //if we cast it to child also will get RE
32
        //Exception in thread "main" java.lang.ClassCastException: com.me.overriding.Parent cannot be cast to com.me.overriding.Child
33
        //at com.me.overriding.ChildParenRule.main(ChildParenRule.java:19)
34
​
35
        //Parent parent2=new Parent();
36
        //((Child) parent).method("Me");
37
​
38
        //Calls the child  lass Method,If not found calls 
39
        //Parent class's Method
40
​
41
        //Child child=new Child();
42
        //child.method("Me");
43
​
44
​
45
        //Though Reference type is Parent overriding occurs at RE
46
        //It will take as child object and calls child method
47
        //if not there it will search for parent class method
48
​
49
        //Parent parent=new Child();
50
        //parent.method("Me");
51
​
52
​
53
        //CE as Type mismatch: cannot convert from Parent to Child
54
        //We can't convert  parent to child class  
55
        //Exception in thread "main" java.lang.Error: Unresolved compilation problems: 
56
        //Syntax error, insert "VariableDeclarators" to complete LocalVariableDeclaration
57
        //Syntax error, insert ";" to complete LocalVariableDeclarationStatement
58
​
59
        //at com.me.overriding.ChildParenRule.main(ChildParenRule.java:53)
60
​
61
        //Child child=(Child) new Parent();
62
        //child.method("Me");
63
​
64
​
65
        //
66
        /*6
67
        down vote
68
        A parent class should not have knowledge of child classes. 
69
        Parent parent=new Parent();
70
        ((Child)parent).method("Me");*/
71
​
72
​
73
​
74
    }
75
}


Instance Methods Are Preferred Over Interface Default Methods

29
1
package com.me.overriding;
2
​
3
//Instance methods are preferred over interface default methods.
4
​
5
//Consider the following classes and interfaces:
6
​
7
class Horse1 {
8
    public String identifyMyself() {
9
        return "I am a horse.";
10
    }
11
}
12
interface Flyer {
13
    default public String identifyMyself() {
14
        return "I am able to fly.";
15
    }
16
}
17
interface Mythical {
18
    default public String identifyMyself() {
19
        return "I am a mythical creature.";
20
    }
21
}
22
public class Pegasus extends Horse1 implements Flyer, Mythical {
23
    public static void main(String...args) {
24
        Pegasus myApp = new Pegasus();
25
        System.out.println(myApp.identifyMyself());
26
    }
27
}
28
​
29
//The method Pegasus.identifyMyself returns the string I am a horse.


The programs having comments to illustrate the usage and consequances while overrding, It might have Some CE and RE.Plese Let me know if you came across any mistake(s) in below programs. 

Java (programming language)

Published at DZone with permission of Madhusudana Singana. See the original article here.

Opinions expressed by DZone contributors are their own.

Partner Resources

×

    April 11, 2017 Daily Digest

  • Merging vs. Rebasing

  • Object-Oriented Analysis and Design (Part 4)

  • Livecoding: A Map of Global Migrations, Part 1

  • All About Overriding in Java

  • Tech Debt- Balance Sheets

  • Python Pandas Tutorial: DataFrame Basics

  • Single Roundtrip Authentication

  • Java Garbage Collectors: When Will G1GC Force CMS Out?

  • Best Practices for Docker and Microservices at Scale

  • Sanitize: Good for Beer, Good for Data

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!