java类实现接口注意问题


/*
  java中,一个类实现某个接口,必须重写接口中的所有方法吗?
 答:抽象类可以不用,普通类必须
 */
class Demo{
	public static void main(String[] args){
		/*
		Person  p = new Person();
		Person  p2 = new Person();
		Person  p3 = new Person();
		*/
		//Animal a = new Cat();
		
		Inst1 myinst = new Inst1();
		myinst.fn0();
		
		new My(){//前面必须加public  
			// 否则:Cannot reduce the visibility of the inherited method from My	Java Problem

			public void fn0(){}
			public int fn1(){}
			 //void fn2(){}   wrong
			public void fn2(){}
			
		};
	}
}
interface My{
	void fn0();
	int fn1();
	void fn2();
}
//1.抽象类实现某个接口 不必全部重写接口中的方法
abstract class Middle implements My{
	public void fn0(){
		System.out.println("haha");
	}
}

/*2.普通类实现某个接口,必须重写接口中的所有方法吗?
class  MyInst implements My{
//	The type MyInst must implement the inherited abstract method My.fn1()	Java Problem
//The type MyInst must implement the inherited abstract method My.fn2()	Java Problem

	public void fn0(){
		System.out.println("haha,creatte myInst");
	}
}
*/
class Inst1 extends Middle implements My{
	public int fn1(){
		return 1;
	}
	//如果屏蔽下面两行语句  则会出现没有实现抽象方法的  错误
	//The type Inst1 must implement the inherited abstract method My.fn2()	Java Problem

	
	public void fn2(){
		System.out.println(11);
	}
}
class Inst2  extends Middle implements My{
	public int fn1(){
		return 2;
	}
	public void fn2(){
		System.out.println(22);
	}
}
class Inst3  extends Middle  implements My{
	public int fn1(){
		return 3;
	}
	public void fn2(){
		System.out.println(33);
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值