false_azure
false_azure

Reputation: 1503

Java - protected 'getters' vs. nested classes

If I have a bunch of fields in a parent class that all need to be inherited by subclasses, is it better to have the subclasses nested in the superclass, make the fields protected rather than private, or use protected accessors? Or some other alternative?

Upvotes: 0

Views: 778

Answers (5)

Sanchit
Sanchit

Reputation: 2260

If you want it to be accessible to a subclass you are left with only two options, public and protected. Protected is probably what you want. The below table applies when you use the extends keyword in java for inheritance.

               Access Levels

Modifier    Class   Package Subclass    World
public      Y       Y       Y           Y
protected   Y       Y       Y           N
no modifier Y       Y       N           N
private     Y       N       N           N

If you NEST the sub class in the super class then you can use private as well. This is because the inner class is PART of the parent class and therefore has access to private methods as well.

public class Parent {
    private int x = 5;

    //Not really a subclass
    private class NestedClass {
        public NestedClass() {
            int hax = new Parent().x; // Works!
        }
    }

    //More of a nestedclass than a subclass.
    private class SubClass extends Parent {
        public SubClass() {
            int stillHax = new Parent().x;
        }
    }
}

You you don't use inheritance until you use the extends or implements keywords so you probably want to have the SubClass extending the Parent class (in a different file) and the variables would have protected (or public) level access. Note that being in the same pakage or in the same class takes prority in the grid. The above two examples work because the other class in in the SAME class as the parent class.

Just follow the grid, that is all.

Upvotes: 1

Adrian Shum
Adrian Shum

Reputation: 40036

There are cases that exposing protected fields or protected accessor methods make sense. So it all depends on your design for the parent class, and how do you want the child class to make use of your parent class.

However, one that that is for sure: "is it better to have the subclasses nested in the superclass" <- This is rarely a correct choice.

Upvotes: 1

Ugur Artun
Ugur Artun

Reputation: 1804

I think using protected accessors the best way and more common approach.

Upvotes: 1

blackpanther
blackpanther

Reputation: 11486

The most easiest solution is make the superclass fields or instance variables protected, however, if you make them private you can always access them through getters and setters which conceptually is much more better because it adheres to the principle of encapsulation.

Upvotes: 3

codebox
codebox

Reputation: 20254

The simplest solution would seem to be to make the fields protected, unless you have a compelling reason to do otherwise, just go with that.

Upvotes: 1

Related Questions