这里写自定义目录标题
java 语言中关于接口的概念
package interfaceTexter;
interface Shape2D{
final double pi=3.14;
public abstract double area();
}
interface color{
void setcolor(String str);
}
public static class circle implements Shape2D,color{
double radius;
String color;
public circle(double r) {
radius=r;
}
public double area() {
return (pi*radius*radius);
}
public void setcolor(String str) {
color=str;
System.out.println("color="+color);
}
}
public static class Rectangle implements Shape2D{
int width,height;
public Rectangle(int w,int h) {
width=w;
height=h;
}
public double area() {
return (width*height);
}
}
public static void main(String[] args) {
//Rectangle rect=new Rectangle(5,6);
//System.out.println("Area of rect="+rect.area());
circle cir=new circle(2.0);
cir.setcolor("blue");
System.out.println("Area of circle="+cir.area());
**在8和17行出现错误:No enclosing instance of type test is accessible.
Must qualify the allocation with an enclosing instance of type test (e.g. x.new A()
where x is an instance of test).
译文是:没有封闭的实例类型测试是可访问的。
必须有资格分配一个封闭测试类型的实例(例如,x。新()其中x是一个实例的测试)。
原因是:内部类Rectangle是动态的,主程序是静态的,在java中,类中的静态方法不能直接
调用动态方法。只有将某个内部类修饰为静态类,然后才能够在静态类中调用该类的成员变量与成员方法
//修改:将public class 修改为public static class**
//接口类型引用变量
Shape2D var1,var2;
var1=new Rectangle(5,6);
System.out.println("Area of rect="+var1.area());
var2=new circle(2.0);
System.out.println("Area of rect="+var2.area());
public class test {
interface Shape{
double pi=3.14;
void setcolor(String str);
}
interface Shape2D extends Shape{
double area();
}
public static class circle implements Shape2D{
double radius;
String color;
public circle(double r) {
radius=r;
}
public double area() {
return (pi*radius*radius);
}
public void setcolor(String str) {
color =str;
System.out.println("color="+color);
}
}
public static void main(String[] args) {
circle cir;
cir=new circle(2.0);
cir.setcolor("blue");
System.out.println("Area="+cir.area());
}
}