0
package practice;

class person{
private String firstname;
private String lastname;

public person(String firstname,String lastname){
    set_first(firstname);
    set_last(lastname);
}

public String get_first() {
    return firstname;
}
public void set_first(String firstname) {
    this.firstname=firstname;
}
public void set_last(String lastname) {
    this.lastname=lastname;
}
public String get_last() {
    return lastname;
}
}

class employee extends person{  
private int empid;  
public employee(String firstname,String lastname,int empid){  
    super(firstname,lastname);  
    set_empid(empid);
}

public void set_empid(int empid) {
    this.empid=empid;
}
public int get_empid() {
    return empid;
}
}

class testing_super_keyword {  
public static void main(String args[]) {  
    employee emp=new employee("John","Jackson",1234);  
    System.out.println(emp.get_first()+"  "+emp.get_last());  
    System.out.println(emp.get_empid());  
}
}

Can anybody explain how the class employee inheriting the class person even when the attributes of the class person "firstname" and "lastname"have been declared as private?

AS of my knowledge a superclass variable declared as private cant be inherited by the sub class.

Aritra Dutta
  • 105
  • 6

1 Answers1

1

This is a considered a good programming practice where you do not give direct access to the instance variables of a class by using private access specifiers and instead provide the public getter and setter methods to get and set the instance variables.

In you case you cannot access the instance variables of SuperClass directly but you have the public getter and setter methods(get_first, set_first) declared and you can make use of them.

Also, as per the Java naming convention use the camelCase names for functions. For example instead of get_name use getName and son on.

Yug Singh
  • 3,112
  • 5
  • 27
  • 52