Pankesh Patel
Pankesh Patel

Reputation: 1302

Limit the scope of the overriden method in Java inheritence

public abstract class SoftwareComponent {

    private Set<Information> generateInfo = new HashSet<Information>();
    private Set<Information>  consumeInfo = new HashSet<Information>();
    public Set<Infomation>  getGeneratedInfo() { ... }
    public Set<Information> getConsumedInfo()  {....}
}

public  class SensorDriver extends SoftwareComponent {

}

public  class Information { ... }

public class SensorMeasurement extends Information {   }

public class command extends Information {     }

Above mentioned code is my program Structure. Now, the situation is Sensor Driver inherits all its parent class method. I want to limit the scope of overridden Method in the sensor driver.

The limit is "Sensor driver" can only generate "Sensor Measurement" information. "Sensor driver" is not allowed to consume "Command" information.

Upvotes: 2

Views: 722

Answers (2)

vinnybad
vinnybad

Reputation: 2102

Any time you're looking at single inheritance as the answer, you could run into problems. I think you actually want to use multiple inheritance (in the form of interfaces). You should consider declaring interfaces which allow you to perform certain actions and perhaps abstract classes that implement some of those interfaces that "group" logical classes together.

As a general rule of thumb, if B is an A, it will inherit all of A. But if B is A except for x, y, and z, you can throw an UnsupportedOperationException, which is acceptable in some cases, but you should really consider restructuring your hierarchy just a little so it all makes more sense.

Upvotes: 0

Ozan
Ozan

Reputation: 4415

You can make your SoftwareComponent generic and make Information a parameter:

public abstract class SoftwareComponent<I extends Information> {

  private Set<I> generateInfo = new HashSet<I>();
  private Set<I> consumeInfo = new HashSet<I>();
  public Set<I> getGeneratedInfo() { ... }
  public Set<I> getConsumedInfo()  {....}
}

public class SensorDriver extends SoftwareComponent<SensorMeasurement> {
}

Upvotes: 2

Related Questions