这个界面有什么问题?
What is wrong with this interface?
界面可以包含正文吗?帮我解决这部分
public interface Figures
{
public void printMessage (String s)
{
System.out.println ("This figure is " + s);
}
public double area (); // to calculate the area of the figure
}
接口是一个完全“抽象的class”,用于将具有空主体的相关方法分组
public interface Figures
{
public void printMessage (String s);
public double area (); // to calculate the area of the figure
}
要访问接口方法,接口必须由另一个 class 使用 implements 关键字(而不是扩展)“实现”(有点像继承)。接口方法的主体由“实现”提供class.
here解释的很好
这是来自w3school
的示例
// Interface
interface Animal {
public void animalSound(); // interface method (does not have a body)
public void sleep(); // interface method (does not have a body)
}
// Pig "implements" the Animal interface
class Pig implements Animal {
public void animalSound() {
// The body of animalSound() is provided here
System.out.println("The pig says: wee wee");
}
public void sleep() {
// The body of sleep() is provided here
System.out.println("Zzz");
}
}
class Main {
public static void main(String[] args) {
Pig myPig = new Pig(); // Create a Pig object
myPig.animalSound();
myPig.sleep();
}
}
从Java8开始,我们可以使用default
关键字
为接口方法提供默认植入
public interface Figures
{
public default void printMessage (String s)
{
System.out.println ("This figure is " + s);
}
public double area (); // to calculate the area of the figure
}
界面可以包含正文吗?帮我解决这部分
public interface Figures
{
public void printMessage (String s)
{
System.out.println ("This figure is " + s);
}
public double area (); // to calculate the area of the figure
}
接口是一个完全“抽象的class”,用于将具有空主体的相关方法分组
public interface Figures
{
public void printMessage (String s);
public double area (); // to calculate the area of the figure
}
要访问接口方法,接口必须由另一个 class 使用 implements 关键字(而不是扩展)“实现”(有点像继承)。接口方法的主体由“实现”提供class.
here解释的很好
这是来自w3school
的示例// Interface
interface Animal {
public void animalSound(); // interface method (does not have a body)
public void sleep(); // interface method (does not have a body)
}
// Pig "implements" the Animal interface
class Pig implements Animal {
public void animalSound() {
// The body of animalSound() is provided here
System.out.println("The pig says: wee wee");
}
public void sleep() {
// The body of sleep() is provided here
System.out.println("Zzz");
}
}
class Main {
public static void main(String[] args) {
Pig myPig = new Pig(); // Create a Pig object
myPig.animalSound();
myPig.sleep();
}
}
从Java8开始,我们可以使用default
关键字
public interface Figures
{
public default void printMessage (String s)
{
System.out.println ("This figure is " + s);
}
public double area (); // to calculate the area of the figure
}