Computer Applications
In what way does the access specifier of the base class have access control over the derived class? Show with the help of an example.
Encapsulation & Inheritance in Java
12 Likes
Answer
Access specifier of the base class have access control over the derived class in the following way:
- Private members of base class cannot be accessed in the derived class.
- Public members of base class can be accessed as public members in the derived class.
- Protected members of base class can be accessed in the derived class and can be inherited by further sub classes.
Below example illustrates this:
class A {
public int x;
protected int y;
private int z;
public A() {
x = 10;
y = 20;
z = 30;
}
public int sum() {
return x + y + z;
}
}
class B extends A {
int total;
void computeTotal() {
/*
* Public method sum() of base class
* is accessible here
*/
total = sum();
}
void display() {
/*
* x is accessible as it is public
*/
System.out.println("x = " + x);
/*
* y is accessible as it is protected
*/
System.out.println("y = " + y);
/*
* This will give ERROR!!!
* z is not accessible as it is private
*/
System.out.println("z = " + z);
}
}
Answered By
7 Likes
Related Questions
Why is the main method in Java so special?
What is meant by scope of variables? Show its application with the help of an example.
Suppose, 'Happening' and 'Accident' are two classes. What will happen when Happening class derives from Accident class by using private visibility?
Give reasons:
(a) In what circumstances is a class derived publicly?
(b) In what circumstances is a class derived privately?