Using secure fields in an abstract class in Java

I am currently participating in a university class in Java, and for coding samples, the professor uses fields protectedto access subclasses.

I asked if it was bad practice, and she was told that it was normal. That's true, why not use setters and getters for abstract methods? I thought it was always best to limit as much information as possible, unless otherwise required.

I tested using setters and getters with a parent abstract, and it works great for parent classes abstractthat are subclasses. Although abstract classes cannot exist , instantiatedthey can still be used to create objects, if subclassany instantiated, as I understand it.

Here is a quick example:

public abstract class Animal {
    protected int height;
}

public class Dog extends Animal {
    public Dog() {
        height = 6;
    }
}

public class Cat extends Animal {
    public Cat() {
        height = 2;
    }
}

In contrast to use:

public abstract class Animal {
    private int height;

    public getHeight() {
        return height;
    }

    public setHeight(int height) {
        this.height = height;
    }
}

public class Dog extends Animal {
    public Dog() {
        setHeight(6);
    }
}

public class Cat extends Animal {
    public Cat() {
        setHeight(2);
    }
}
+6
source share
2 answers

Although you can certainly use both methods, the protectedfield path is less desirable, and I would argue less idiomatic, especially if this is the library code that you plan to share.

This can be seen in the Java Collections API, as well as in Guava. It will be difficult for you to find Abstractclasses with protectedfields (not to mention any fields).

There are always exceptions, and you do not always write the library code (i.e. public API).

protected / private . , , :

public abstract class Animal {
    private int height;
    public Animal(int height) { this.height = height; }
    public int getHeight() { return this.height }
}

public class Cat extends Animal {
    public Cat() {
        super(2);
    }
}

, , .

+3

Animal . setter. . ?

+1

Source: https://habr.com/ru/post/1611700/


All Articles