Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java overriding private vs public

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)

like image 342
Donald Avatar asked Oct 30 '25 18:10

Donald


1 Answers

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.

like image 174
ΦXocę 웃 Пepeúpa ツ Avatar answered Nov 01 '25 07:11

ΦXocę 웃 Пepeúpa ツ