In: Computer Science
Consider the DataSource class in below code. Explain how inheritance is intended to be used with this class. Does this represent a good use of inheritance? Explain your answer
// Base class for game configuration
public abstract class DataSource {
private Graph map;
private HashMap <String,Room> rooms;
private ArrayList <Entity> entities;
private Player player;
protected HashMap < String, List<String[]> > tables;
// constructor
public DataSource() {
}
// Connect to the data source. Override if source is a database
public void connect() {
};
// Load the configuration tables required to build the game world
public abstract void load();
// Build the game world
public final void build() {
// code omitted
}
// Disconnect from the data source. Override if source is a database
public void disconnect() {
};
// Get a the layout of the game world
public Graph getMap() {
return map;
}
// Get room details. The HashMap key is the room label.
public Map <String,Room> getRooms() {
return rooms;
}
// Get player details
public Player getPlayer() {
return player;
}
// Get entity (bats, bird, monsters, wumpus) locations
public List <Entity> getEntities() {
return entities;
}
}
Inheritance
Yes, this class represents good use of inheritance.
Some unnecessary things you need to remove
are:
1. unnecessary semi-colon at end of connect method
2. same with disconnect method
Some things you need to add:
1. Since there is no built-in(primitive) datatype named 'Player'
in java, so you definitely have to create Player class.
2. Same, you'd have to create Room class
Also, it has load method which is abstract which would
be implemented by child classes.
An example of how to use it (in child class) is as follows:-
public DataBase extends DataSource {
/*
We can access protected field which
is tables in our case
We cannot access other fileds, just
can access public methods
*/
public static void main(String[] args) {
}
@Override
public void load() {
}
// And if we want to implement connect/disconnect methods, do it as following:-
@Override
public void connect() {
super.connect(); # A call to
super(parent) class which is DataSource class's connect
method
}
@Override
public void disconnect() {
super.disconnect();
}
}
-------------------------------------------------------------------
COMMENT DOWN FOR ANY QUERIES!!!
HIT A THUMBS UP IF YOU DO LIKE IT!!!