Member Access and Inheritance in Java

Member Access and Inheritance in Java

exploreJava logo

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){ = 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");; } } Output: First Student: Name: Gagan
************* Second Student: Name: Ankeet Age: 25
Mobile: 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();
p = s1;
System.out.println("Showing using s1");;
System.out.println("Showing using p");;

Output Showing using s1 Name: Ankeet Age: 25 Mobile: 9811196411
Showing using p Name: Ankeet Age: 25
Mobile: 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

Post a Comment