栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

2021-10-28

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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());
	}
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/353287.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号