Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restricting parent class members to its immediate child class only

Suppose I have four classes in java with given hierarchy.

class A {}
class B extends A {} 
class C extends B {} 
class D extends C {} 

As per my understanding all the accessible fields of class A will be available to all its child classes through inheritance. Now what if I want few fields of class A to be available to class B only.

Is there any way in java so that I can restrict certain fields of parent class to its immediate child class only?

like image 252
user8001621 Avatar asked Nov 23 '17 04:11

user8001621


People also ask

Can a child class access private members of parent class?

A subclass does not inherit the private members of its parent class. However, if the superclass has public or protected methods for accessing its private fields, these can also be used by the subclass. A nested class has access to all the private members of its enclosing class—both fields and methods.

What is the relationship between parent class and child class?

A parent can be a child in another relationship. A parent class instance can exist without a child class instance. Every child class has only one parent class, but a parent class can have more than one child class. In terms of databases, a parent class has a one-to-many relationship with a child class.

Can a parent class have more than one child class?

Multiple classes can be derived from a single parent. There is no limit to the number of children a class can have (but a child can have only one parent). Two children of the same parent are called siblings. Siblings are NOT related to each other by inheritance.

Can parent class inherit from child class?

Inheritance concept is to inherit properties from one class to another but not vice versa. But since parent class reference variable points to sub class objects. So it is possible to access child class properties by parent class object if only the down casting is allowed or possible....


1 Answers

Not that I would do anything like this in production, but here you go:

class A {
    private int a = 1;

    public int getA() {
        if (getClass().equals(A.class) || 
            getClass().getSuperclass().equals(A.class)) {
            return a;
        } else {
            throw new UnsupportedOperationException("hahaha");
        }
    }        

    public static void main(String[] args) {
        A a = new A();
        B b = new B();
        C c = new C();
        System.out.println(a.getA());
        System.out.println(b.getA());
        System.out.println(c.getA());
    }
}

class B extends A {}

class C extends B {}

So basically you can use this trick to allow only classes you want (using either the blacklist or whitelist approach) - to call getA().

OUTPUT:

1
1
Exception in thread "main" java.lang.IllegalStateException: hahaha
    ...
like image 118
Nir Alfasi Avatar answered Oct 17 '22 09:10

Nir Alfasi