Why can't my subclass access a protected variable of its superclass, when it's in a different package?

前端 未结 4 1534
梦谈多话
梦谈多话 2020-11-29 05:55

I have an abstract class, relation in package database.relation and a subclass of it, Join, in package database.operations

4条回答
  •  清酒与你
    2020-11-29 06:29

    It works, but only you the children tries to access it own variable, not variable of other instance ( even if it belongs to the same inheritance tree ).

    See this sample code to understand it better:

    //in Parent.java
    package parentpackage;
    public class Parent {
        protected String parentVariable = "whatever";// define protected variable
    }
    
    // in Children.java
    package childenpackage;
    import parentpackage.Parent;
    
    class Children extends Parent {
        Children(Parent withParent ){
            System.out.println( this.parentVariable );// works well.
            //System.out.print(withParent.parentVariable);// doesn't work
        } 
    }
    

    If we try to compile using the withParent.parentVariable we've got:

    Children.java:8: parentVariable has protected access in parentpackage.Parent
        System.out.print(withParent.parentVariable);
    

    It is accessible, but only to its own variable.

提交回复
热议问题