J.Olufsen
J.Olufsen

Reputation: 13915

Cannot initialize in child the field defined in parent

How to define field in parent class and assign value in child to this field so it will be accessible for type Room? I think this int bound = 3; will hide parent variable...

public abstract class Room {public int bound; }

public class DarkRoom extends Room {

     bound = 3;
}

Upvotes: 2

Views: 124

Answers (2)

Óscar López
Óscar López

Reputation: 236114

Assign the field in the constructor, not in the class declaration:

public class DarkRoom extends Room {
    public DarkRoom() {
        bound = 3;
    }
}

Upvotes: 4

Eugene Retunsky
Eugene Retunsky

Reputation: 13139

You can use a class initialization block:

public class DarkRoom extends Room {
   {
     bound = 3; // error VariableDeclaratorId expected after this token
         // int bound = 3; // hiding?
    }
}

or perform the initialization in a method or a constructor of the DarkRoom class.

Upvotes: 1

Related Questions