2021-10-28

这里写自定义目录标题


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());
	}
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值