Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how does inheritance work with abstract classes in java

I am writing small pieces of code to make sure I understand Java basics and I have the following.

package teams1;

public abstract class Team1{
    private String sport = new String();

    public abstract String getSport();

    public abstract void setSport();
}

import teams1.*;
abstract class FootballTeam1 extends Team1{

    public String getSport(){
        return "Football";
    }

    public void setSport(){
        this.sport="Football";
    }
}

It doesn't compile because sport is private in the super class, but I thought FootballTeam1 would inherit it's own copy of sport because it is extending Team1. Any help would be appreciated. Thanks!

like image 265
ponder275 Avatar asked Sep 16 '26 10:09

ponder275


2 Answers

You have mostly answered your own question. FootballTeam1 does not have access to the private fields of its parent. That is what the 'protected' scope is used for.

However, the child FootballTeam1 does have its own copy of the field. It has a copy of all fields that the parent class has, which I can see would cause confusion.

The reason for this distinction is modularity. A subclass of a parent class only has access to the parts of the parent class that one has explicitly stated that it may have access to. This allows developers to consider what parts of a class are to be exposed, under the Object Orientated goal known as the 'Open/Closed Principle'; that is, classes should be open for extension, but closed for modification.

The quickest 'fix' to the class is change the scope of the field, for example

private String sport = new String();

becomes

protected String sport = new String();

or

public String sport = new String();

If you do not want to give the child class direct access to the field, but do want to allow it to change the field then a protected setter method could be used. For example, you could add the following to Team1.

protected void setSport( String newValue ) {
    this.sport = newValue;
}
like image 180
Chris K Avatar answered Sep 18 '26 22:09

Chris K


Since the class variable sport is private, it is private to the class it was declared in. Extending classes cannot access this variable in the manner you are trying.

Try making the variable protected (which allows extending classes to have visibility on the variable) if you want to continue accessing the sport variable in this manner, otherwise have getters and setters in the abstract class and the extending/implementing classes to call them instead.

like image 23
Ocracoke Avatar answered Sep 18 '26 23:09

Ocracoke