
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Why Subclass Doesn't Inherit Private Instance Variables of Superclass in Java
When you declare the instance variables of a class private, you cannot access them in another class if you try to do so a compile-time error will be generated.
But, if you inherit a class that has private fields, including all other members of the class the private variables are also inherited and available for the subclass.
But, you cannot access them directly, if you do so a compile-time error will be generated.
Example
class Person{ private String name; public Person(String name){ this.name = name; } public void displayPerson() { System.out.println("Data of the Person class: "); System.out.println("Name: "+this.name); } } public class Student extends Person { public Student(String name){ super(name); } public void displayStudent() { System.out.println("Data of the Student class: "); System.out.println("Name: "+super.name); } public static void main(String[] args) { Student std = new Student("Krishna"); } }
Compile-time error
Student.java:17: error: name has private access in Person System.out.println("Name: "+super.name); ^ 1 error
To access the private members of the superclass you need to use setter and getter methods and call them using the subclass object.
Example
class Person{ private String name; public Person(String name){ this.name = name; } public void setName(String name) { this.name = name; } public String getName() { return this.name; } public void displayPerson() { System.out.println("Data of the Person class: "); System.out.println("Name: "+this.name); } } public class Student extends Person { public Student(String name){ super(name); } public void displayStudent() { System.out.println("Data of the Student class: "); } public static void main(String[] args) { Student std = new Student("Krishna"); System.out.println(std.getName()); } }
Output
Krishna
Advertisements