Member Access and Inheritance in Java
A subclass includes all the members of its superclass, but it can't access the private members of its superclass, it can access only the public and protected members of its superclass. The priave members of superclass remain private to itself.
class person {protected String name;private int age;private String mobileno;public void set(String name,int age,String mobileno){this.name = name;this.age = age;this.mobileno = mobileno;}public void showName(){System.out.println("Name: "+name);}public void show(){System.out.println("Name: "+name+"\nAge: "+age+"\nMobile: "+mobileno);}}class student extends person{ String school; public void set(){ name = "Gagan"; //age = 81; not possible //mobileno = "9898989898"; not possible } public void set(String name,int age, String mobileno){ super.set(name,age,mobileno); } } class access_inheritance{ public static void main(String [] args){ student s = new student(); System.out.println("First Student:"); s.set(); s.showName(); System.out.println("Second Student:"); s.set("Ankeet",25,"9875421021"); s.show(); } } Output: First Student: Name: Gagan
************* Second Student: Name: Ankeet Age: 25Mobile: 9875421021
A superclass object can reference a subclass object
We can assign reference of a subclass "B" to a object of superclass "A" if the subclass B extends the superclass A. In the code given below, reference (object) of subclass is assigned to reference (object) to superclass.
class access_inheritance_II{public static void main(String [] args){person p = new person();student s1 = new student();s1.set("Ankeet",25,"9811196411");p = s1;System.out.println("Showing using s1");s1.show();System.out.println("Showing using p");p.show();}}Output Showing using s1 Name: Ankeet Age: 25 Mobile: 9811196411
*******************Showing using p Name: Ankeet Age: 25Mobile: 9811196411
In the above code, one object "p" object class person and one object of "s1" class student are created. The variables for s1 is set. Then reference of s1 is assigned to p, then show() method is called using p. Both objects will show the same values.
The superclass reference variable can access only those parts of the object of subclass defined by the superclass. If a member variable named grade is defined in subclass student, the object of person class can't access that grade member of the student class.
Threads in Java
Inheritance in Java