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.
上一篇: 在iPhone应用程序中使用SSL
下一篇: 抽象类或使用接口的公共方法