How to access the private variables of a class in its subclass?

前端 未结 28 2317
清歌不尽
清歌不尽 2020-12-17 09:46

This is a question I was asked in an interview: I have class A with private members and Class B extends A. I know private members of a class cannot be accessed, but the qu

28条回答
  •  伪装坚强ぢ
    2020-12-17 10:20

    Below is the example for accessing the private members of superclass in the object of subclass.

    I am using constructors to do the same.

    Below is the superclass Fruit

    public class Fruit {
        private String type;
    
        public Fruit() {
        }
    
        public Fruit(String type) {
            super();
            this.type = type;
        }
    
        public String getType() {
            return type;
        }
    
        public void setType(String type) {
            this.type = type;
        }
    
    }
    

    Below is subclass Guava which is inheriting from Fruit

    public class Guava extends Fruit{
        private String name;
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public Guava(String name,String type) {
            super(type);
            this.name=name;
        }
    }
    

    Below is the main function where we are creating an object of subclass and also displaying the member of superclass.

    public class Main {
    
        public static void main(String[] args) {
    
            Guava G1=new Guava("kanpuria", "red");
            System.out.println(G1.getName()+" "+G1.getType());
    
        }
    
    }
    

提交回复
热议问题