Access a private variable from the superclass (JAVA)

后端 未结 6 2077
终归单人心
终归单人心 2021-02-08 20:19

Ok so I have studied java all semester and thought I had a clear understanding about inheritance and super/sub classes. Today we were given as assignment for making a superclass

6条回答
  •  甜味超标
    2021-02-08 21:10

    The part

    Any access to an a variable must be done through protected methods in the sub classes.
    

    ... just means that the subclasses have to call protected methods that are defined in the superclass. Since these methods are protected they can be accessed by the subclasses.

    First you would define a base class like this:

    public class Base {
    
        private int x;  // field is private
    
        protected int getX() {  // define getter
            return x;
        }
    
        protected void setX(int x) {  // define setter
            this.x = x;
        }
    }
    

    Then you would use it in your child class like this:

    class Child extends Base{
    
        void foo() {
            int x = getX(); // we can access the method since it is protected.
            setX(42);  // this works too.
        }
    }
    

提交回复
热议问题