Search code examples
javainheritanceinterface

How do I replace an abstract method with an interface method?


I have a couple java files in a package stacks package.

The first one is an abstract class Stack class that has a public abstract void print() method in it.

The second one is a public interface FancilyPrint interface that has a void fancyPrint() method in it.

I am now working on a public class LinkedListStack extends Stack implements FancyPrint class.

How do I write a fancyPrint() method that satisfies the interface contract, without writing a useless void print() method from the abstract class? It is useless to have a standard print() method in this class due to it implementing the interface with its own fancyPrint() method. I don't remember how to do this.

Here are my classes for reference:

Stack.java:

package stacks;

public abstract class Stack<AnyType>
{
    public abstract void push(AnyType data);

    public abstract AnyType pop();

    public abstract AnyType peek();

    public abstract boolean isFull();

    public abstract boolean isEmpty();

    public abstract void print();
}

LinkedListStack.java

package stacks;

import linkedlists.*;

public class LinkedListStack<SomeType> extends Stack<SomeType> implements FancyPrint
{
    LinkedList<SomeType> l = new LinkedList<>();
    
    @Override
    public void push(SomeType data)
    {
        l.head_insert(data);
    }

    @Override
    public SomeType pop()
    {
        return l.delete_head();
    }

    @Override
    public SomeType peek()
    {
        return l.headData();
    }

    @Override
    public boolean isFull()
    {
        return false;
    }

    @Override
    public boolean isEmpty()
    {
        return l.isEmpty();
    }

    @Override
    public void fancyPrint()
    {
        
    }

    // I do not need this method for this class. I will need it for other classes
    // that extend the Stack abstract class.
    @Override
    public void print()
    {

    }

FancilyPrint Interface:

package stacks;

public interface FancilyPrint
{
    void fancyPrint();
}

Solution

  • I think you should exclude print method from Stack class and create one more interface SimplePrintable having print method. So LinkedListStack will implement FancyPrintable but other classes will implement SimplePrintable.