3

I'm learning about overriding at the moment and I read that a private method cannot be overridden here

I also read that the access level cannot be more restrictive than the superclasses access level here

So what I'm wanting to know is, does this mean you can only override public methods? And you're new method must also be public?

Scenario

class A {
    private void method1(){
        ....
    }
}

class B extends A {
    private void method1(){
        ....
    }
}

Am I correct in saying this will be a compile time error because private methods cannot be overridden?

Scenario2

class A {
    public void method1(){
        ....
    }
}

class B extends A {
    private void method1(){
        ....
    }
}

Am I correct in saying this will also produce a compile time error because you the access level of method1() in B is more restrictive than method1() in A

Scenario3

class A {
    public void method1(){
        ....
    }
}

class B extends A {
    public void method1(){
        ....
    }
} 

Final question, is this the only scenario methods can be overridden? (both access levels are public)

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
Donald
  • 117
  • 6

2 Answers2

4

suppose the class:

class A {
    public void method1() {         }

    protected void method2() {         }

    private void method3() {         }

    void method4() {         }
}

then

class B extends A {
    @Override
    public void method1() {
        // this method DOES override the Method1
    }

    @Override
    protected void method2() {
        // this method DOES override the Method2
        super.method2();
    }

    private void method3() {
        // this method DOES NOT override the Method3
    }

    @Override
    void method4() {
        // this method DOES override the Method4
        super.method4();
    }
}

and in all the cases your overridden method cannot be less visible than the method from the super class.

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
1

Yes, you can override public or protected methods. You cannot override private methods.

That said, your first snippet will not produce compilation error. Both A and B will have a method1(), but B's method will not be overriding A's method.

The second snippet will indeed fail to pass compilation, since you cannot reduce the visibility of an inherited method.

The third snippet is the only case of method overriding in the code you posted.

Eran
  • 387,369
  • 54
  • 702
  • 768