Question

I am not sure why in a context like the following

class Parent {

    private void method1() {
        System.out.println("Parent's method1()");
    }


    public void method2() {
        System.out.println("Parent's method2()");
    }   

}


public class Child extends Parent {

    public void method1() {
        System.out.println("Child's method1()");                
    }


    public static void main(String args[]) {
        Parent p = new Child();
        p.method2();
    }

}

Parent may be package private, but not protected.

Specifically the error generated is

modifier protected not allowed here

Which would seem to indicate that it is an issue of access privilege - but I am suspicious that this may be a red herring. Private modifier also generates an error (naturally).

Était-ce utile?

La solution

In Java, Top level classes can have only package private and public modifiers.

Making a class private doesn't make any sense. If no one use that class for any reason, then why we need that class?

protected access modifier means, only visible within the enclosing class and any subclasses, and also anywhere in the enclosing class's package. No body knows which classes going to be subclass of a protected class. So, it also doesn't make sense

But both private and protected can be (and frequently are) applied to nested classes and interfaces, just never top-level classes and interfaces

Autres conseils

You cannot use the protected access modifier for top level classes.

according to the spec $8.1.1

The access modifier public (§6.6) pertains only to top level classes (§7.6) and to member classes (§8.5), not to local classes (§14.3) or anonymous classes (§15.9.5).

The access modifiers protected and private (§6.6) pertain only to member classes within a directly enclosing class or enum declaration (§8.5).

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top