Search code examples
javainheritanceencapsulation

How to implement multiple subclasses with the same methods that use encapsulation?


I want to create a simple game in Java. I'm struggling to understand how to use inheritance to accomplish how to implement subclasses that use encapsulation without needing to write out the same methods in the subclasses.

Ideally I'd like to make one base class "character" with a bunch of methods that use encapsulation, so that I can just declare different values for the private members of the subclasses. So something like,

public class Character {
private int hitPoints;
public int getHitPoints(){return hitPoints;}
}

And then just declare different values for the variables.

public class subCharacter extends Character {
private int hitPoints=100;
//getHitPoints() already inherited and should return 100
}

But to properly get the hit points of the subclass. I have to declare the same method in the subclass to actually get the method to work.

So isn't encapsulation incompatible with inheritance? Is there something basic here I'm misunderstanding or completely overlooking?


Solution

  • You should make the variable hitPoints protected in you Character class, and set it to 100 in the constructor of the subCharacter class. There is no need for the declaration of the getHitPoints method in the subclass. The code would look like this:

    public class Character {
        protected int hitPoints;
        public int getHitPoints(){return hitPoints;}
    
    }
    
    public class subCharacter extends Character {
        public subCharacter () {
            hitPoints = 100;
        }
    }
    

    Example of a subCharacter object:

    subCharacter sub = new subCharacter();
    System.out.println(sub.getHitPoints()); // prints 100