class

You cannot override a private or a private final method

This is an example explaining why you cannot override a private or a private final method. The example is described in short:

  • We have created three classes, WithFinals, OverridingPrivate that extends WithFinals and OverridingPrivate2 that extends OverridingPrivate.
  • All three classes consist of a public final f() method and a private g() method.
  • We create a new instance of OverridingPrivate2 class. We call its f() method and its g() method. The methods invoked will be the ones in the OverridingPrivate2 class. 
  • We can upcast the OverridingPrivate2 object to OverridingPrivate, and we can also cast OverridingPrivate object to WithFinals, but we cannot call their methods because they are not visible. 

Let’s take a look at the code snippet that follows:  

package com.javacodegeeks.snippets.core;

class WithFinals {
    // Identical to "private" alone:

    private final void f() {

  System.out.println("WithFinals.f()");
    }

    // Also automatically "final":
    private void g() {

  System.out.println("WithFinals.g()");
    }
}

class OverridingPrivate extends WithFinals {

    private final void f() {

  System.out.println("OverridingPrivate.f()");
    }

    private void g() {

  System.out.println("OverridingPrivate.g()");
    }
}

class OverridingPrivate2 extends OverridingPrivate {

    public final void f() {

  System.out.println("OverridingPrivate2.f()");
    }

    public void g() {

  System.out.println("OverridingPrivate2.g()");
    }
}

public class FinalOverridingIllusion {

    public static void main(String[] args) {

  OverridingPrivate2 op2 = new OverridingPrivate2();

  op2.f();

  op2.g();

  // You can upcast:

  OverridingPrivate op = op2;

  // But you can't call the methods:

  //! op.f();

  //! op.g();

  // Same here:

  WithFinals wf = op2;

  //! wf.f();

  //! wf.g();

    }
} 

Output:

OverridingPrivate2.f()
OverridingPrivate2.g()

  
This was an example explaining why you cannot override a private or a private final method in Java.

Byron Kiourtzoglou

Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button