HELLO WORLD--一起加|

kingwzun

园龄:3年6个月粉丝:111关注:0

接口(interface)

本质

本质上就是一个宽泛的抽象类

作用

public interface Shape1 {
int a=1;
//系统自动增加成为:
// public static final int a=1;
double length();
double area();
//系统自动添加成为:
// public abstract double area();
}

使用1

public class Trigangle implements Shape1 {
//Shape 里面有a,不能与Shape里面的变量重名
int a1;
int a2;
int a3;
public Trigangle()
{
this(a,a,a);
}
public Trigangle(int a1, int a2, int a3) {
super();
this.a1=a1;
this.a2=a2;
this.a3=a3;
}
public double length() {
return a1+a2+a3;
}
public double area() {
double p=length()/2;
return Math.sqrt(p*(p-a1)*(p-a2)*(p-a3));
}
}

使用2

public class ShapeTest {
public static void main(String[] args) {
Shape1 shape;
shape =new Trigangle();//此时接口相当于上转型对象
System.out.println(shape.area());//多态
System.out.println(shape.length());
shape =new Y();
System.out.println(shape.area());
shape= new C();
System.out.println(shape.area());
}
}

优点(比较抽象类)

一个类可以继承一个类,但可以同时实现(继承)多个接口

public class Child extends Fathter implements Shape1,Interface1{
}

接口可以继承多个接口

public interface Interface2 extends Interface1,Shape1{
}

匿名内部类

(类没有名字)(用接口创建了一个上转型对象)

和普通类对比

普通类可以创建多个对象,而匿名内部类只能创建一个

举例

接口:Shape

package prj4;
public interface Shape {
int a=1; //public static final
double length();
double area(); //public abstract
}

主函数

package prj4;
public class Graph {
public static void main(String[] args) {
Shape shape1=new Shape() {
public double length() {
// TODO Auto-generated method stub
return 10;
}
public double area() {
// TODO Auto-generated method stub
return 1010;
}
};
System.out.println(shape1.area());
System.out.println(shape1.length());
}
}

实战

计算各种图形的周长 <接口|继承|多态|分割字符串>

本文作者:kingwzun

本文链接:https://www.cnblogs.com/kingwz/p/15428952.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   kingwzun  阅读(272)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起