简体   繁体   中英

Abstract class or public method using interface

Shape.java

public interface Shape {
    String draw();

    void calcSomething();
}

Square.java

public class Square implements Shape {
    @Override
    public String draw() {
        return "SQUARE";
    }

    @Override
    public void calcSomething() {

    }
}

When I implement an interface , the method that I implemented must be public .

I want to make draw() public method but calcSomething() private or protected .

I've gone through Interfaces in Java: cannot make implemented methods protected or private . And there no straight way to do this

So instead of using interface I'm planning to use abstract class

Shape.java using abstract class

public abstract class Shape {
    abstract public String draw();

    abstract protected void calcSomething();
}

Square.java that implements Shape abstract class

public class Square extends Shape {
    @Override
    public String draw() {
        return "SQUARE";
    }

    @Override
    protected void calcSomething() {

    }
}

Which one should I choose. Should I use interface and make the calcSomething() public or Should I use abstract class and make the calcSomething() protected

Quoting The Java™ Tutorials - What Is an Interface? :

Implementing an interface allows a class to become more formal about the behavior it promises to provide. Interfaces form a contract between the class and the outside world .

In order for the outside world to access the methods, they must be public.

If you don't want the method to be public, ie callable from the outside world, then it doesn't belong in the interface.

If you want calcSomething() to be callable from other code in Shape , then ... Oops, there is no other code in Shape . It's an interface.
Ok, if you want calcSomething() to be callable from other code in Square , you need it to be an abstract (or stub) method. This is for example how the template method pattern works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM