创建一个实现其自身方法的接口

And*_*een 0 java interface text-files

我想创建一个在Java中实现它自己的一些方法的接口(但是语言不允许这样做,如下所示):

//Java-style pseudo-code
public interface Square {
    //Implement a method in the interface itself
    public int getSize(){//this can't be done in Java; can it be done in C++?
        //inherited by every class that implements getWidth()
        //and getHeight()       
        return getWidth()*getHeight();
    }
    public int getHeight();
    public int getWidth();
}

//again, this is Java-style psuedocode
public class Square1 implements Square{

    //getSize should return this.getWidth()*this.getHeight(), as implemented below

    public int getHeight(){
        //method body goes here
    }

    public int getWidth{
        //method body goes here
    }
}
Run Code Online (Sandbox Code Playgroud)

是否有可能在C++中创建一个可以实现某些自己的方法的接口?

Ale*_*ood 7

使用abstract class:

public abstract class Square {

    public abstract int getHeight();

    public abstract int getWidth();

    public int getSize() {
        return getWidth() * getHeight();
    }
}
Run Code Online (Sandbox Code Playgroud)


Psh*_*emo 5

它必须是接口吗?也许抽象课会更好.

public abstract class Square {
    public int getSize() {
        return getWidth() * getHeight();
    }

    //no body in abstract methods
    public abstract int getHeight();
    public abstract int getWidth();
}

public class Square1 extends Square {

    public int getHeight() {
        return 1;
    }

    public int getWidth() {
        return 1;
    }
}
Run Code Online (Sandbox Code Playgroud)