欢迎光临散文网 会员登陆 & 注册

java接口详解

2022-06-21 14:18 作者:虚云幻仙  | 我要投稿

/**
* 测试接口 interface
*/

public interface Sheeny {
   //接口用interface 不再是class
   int LUMINANCE = 2000;
   //接口只能定义常量和方法 默认修饰 public static final int
   void shine();
   //和抽象类一样不写方法体 默认public abstract修饰 子类必须实现
}

interface Long{
   void pl();

   default void def(){
       System.out.println("接口还可以定义默认方法,接口的默认方法必须用default修饰");
       System.out.println("默认方法必须要有方法体实现,子类不必须重写实现,可直接调用");
   }
}

class Mouse implements Sheeny{
   //定义类 实现implements 接口    不再是继承extends
   //Mouse为Sheeny接口的实现类

   @Override
   public void shine() {
       System.out.println("mouse.shine");
   }
}

class Wand implements Long{
   @Override
   public void pl() {
       System.out.println("Wand.pl");
   }
}

class LaserSword implements Sheeny,Long{
   //一个类可以实现多个接口
   @Override
   public void shine() {
       //实现的抽象方法也同样要求public
       System.out.println("LaserSword.shine");
   }

   @Override
   public void pl() {
       System.out.println("LaserSword.pl");
   }

   int a = LUMINANCE;
   //常量直接调用
}

class Test{
   public static void main(String[] args) {
       Mouse m1 = new Mouse();
       int a = m1.LUMINANCE;
       //和继承一样 Mouse实现Sheeny接口后可以通过对象m1.调用LUMINANCE常量

       Sheeny l1 = new LaserSword();
       //和继承中的 父类引用指向子类地址 相同 接口可以声明引用变量类型 不能new创建实例
       a += l1.LUMINANCE;
       //l1.pl()报错 编译类型无法使用执行时类型的方法

       Wand w1 = new Wand();
       w1.def();
       //Wand类可以直接调用接口的默认方法 也可以重写
   }
}

interface P1{
   static void printP1(){
       //接口中可以定义静态方法 默认修饰 public static
       System.out.println("P1.instance initializer");
   }
}

class P2 implements P1{
   {
       /*
       printP1()报错,接口的静态方法只能通过接口调用
       实现类无法直接调用 这和继承不同
       继承中子类可以在类内直接调用父类的静态方法
        */

   }
}

class P3{
   public static void main(String[] args) {
       P1.printP1();
       /*
       P2.printP1()报错,接口的静态方法不属于实现类
       无法通过实现类调用接口的静态方法 这和继承不同
       继承中子类继承了父类的静态方法 通过P1.printP1()或者P2.printP1()都可以调用该方法
        */

   }
}

class P4 implements P1{
   static void printP1(){
       System.out.println("实现类可以定义同名静态方法,但不属于重写");
       System.out.println("该静态方法和接口的同名方法是两个相互无关的方法");
   }
}

interface A1{
   void pa1();
}

interface A2{
   void pa2();
}

interface A3 extends A1,A2{
   //接口可以多继承 子接口会继承父接口的一切
   void pa3();
}

class A4 implements A3{
   //实现类需要实现pa3()以及A3继承自A1A2的pa1()pa2()

   @Override
   public void pa1() {
   }
   @Override
   public void pa2() {
   }
   @Override
   public void pa3() {
   }
}

java接口详解的评论 (共 条)

分享到微博请遵守国家法律