subclasses common methods implemented in abstract superclass with different constructors

StackOverflow https://stackoverflow.com/questions/22603440

  •  20-06-2023
  •  | 
  •  

I know that this has been discussed already here but i have something to add up to that question. I need to make an abstract class called AbstractGraph, and it has to be extended by two types of graph implementations: one uses a matrix, the other one uses lists.

So far i have something like this:

abstract class AbstractGraph implements Graph {

    public void removeAllEdges(){
        //implementation here 
    }

}

and the subclasses:

public GraphMatrix(){
    GraphMatrix()
    {
        //implementation for matrix type 
    }
}

public GraphList(){
    GraphList()
    {
        //different implementation for lists type
    }
}

both implementations would have the same removeAllEdges() method written exactly the same, so i guess it has to be placed in the abstract class. My question is, how do i get to use references to this from inside the abstract class ? Do i have to fill the implementations with getters and setters ? If so, what would be the benefit of using a single implementation of a method for two (or more) subclasses.

有帮助吗?

解决方案

You can use the same code for removeAllEdges as long as it does not depend on the underlying structure (e.g., the matrix or the list) or the functionality is implemented by encapsulated methods that use the underlying graph structure (e.g., getters, setters, and other common methods that you may need). In my perspective, the latter methods would be the abstract methods of this class, since they need to be implemented according to the underlying graph structure.

One of the benefits is code reuse. You write once, and use it in every graph implementation. In your case you have two graph classes, but you may end up having multiple representations for graphs depending on your application. Writing general methods is a nice way of saving time spent in coding, and it also helps you to maintain your code in a more efficient and organized way. The debugging is also easier!!

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top