java编程思想-接口

来源:互联网 发布:中国人工智能产品 编辑:程序博客网 时间:2024/05/19 14:38

1.抽象类和抽象方法

  abstract void f()仅有申明而没有方法体

 如果一个类包含一个或多个抽象方法这个类必须被限定为 抽象,一个抽象类中可以有或者可以没有抽象方法。

abstract class Intrument{
public abstract void play();
}

抽象类不能创建一个对象

继承一个抽象类

abstract class Intrument{
public abstract void play();
}
class Wind extends Intrument{
public void play(){
System.out.print("wind.play()");
}
}
public class test {
public static void main(String[] args) {
// TODO Auto-generated method stub
     Wind wind=new Wind();
     wind.play();
}
}

2.接口

interface产生了一个完全抽象的类,它根本就没有提供任何实现。接口只是提供了形式,而从未提供任何具体实现。也就是说接口中所有的方法必须都是没有具体实现的.

 interface Intrument{
//public abstract void play();
void play();
}
class Wind implements Intrument{
public void play(){
System.out.print("wind.play()");
}
}
public class test {
public static void main(String[] args) {
// TODO Auto-generated method stub
// Intrument y=new Intrument();
     Wind wind=new Wind();
     wind.play();
}
}。

如果在 interface前面不添加public关键字,那么它就具有包访问权限,这样它就只能在同一个包中可用

例如有一包to

/**
 * 
 */
package to;
public interface Intrument {
   void play();
}

有一个包com

package com;
import to.*;
class Wind implements Intrument{
public void play(){
System.out.print("wind.play()");
}
}
public class test {
public static void main(String[] args) {
// TODO Auto-generated method stub
// Intrument y=new Intrument();
     Wind wind=new Wind();
     wind.play();
}
}

那么包to中的接口必须申明为public,否则会出错。

0 0