抽象类和接口

抽象类

public class Abst
{
    public static void main(String[] args)
    {
        Animal cat=new Cat("xiaohong",111);
        Animal dog=new Dog("xiaoming",222);
        cat.go();
        dog.go();
    }
}
abstract class Animal
{
    String name;
    int height;
    public abstract void go();
}
class Dog extends Animal
{
    public Dog(){

    }
    public Dog(String name,int height)
    {
        this.name=name;
        this.height=height;
    }
    public  void go()
    {
        System.out.println(name+" can run and it's height is "+height);
    }
}
class Cat extends Animal
{
    public Cat() {

    }
    public Cat(String name,int height)
    {
        this.name=name;
        this.height=height;
    }
    public void go()
    {
        System.out.println(name+" can and it's height is "+height);
    }
}
抽象类是用abstract所修饰的类
   	抽象方法一定存在于抽象类中,抽象类中不一定有抽象方法
    抽象类可以被继承,抽象类的子类必须重写抽象类中的所有抽象方法,否则编译出错
    抽象方法没有方法体,抽象方法是有子类重写来实现的
	abstract不能与 final,static,private 这些关键字组合
    抽象类定义语法abstract class 类名{···}

接口(interface)

public class Abs
{
    public static void s(Canswim x) {
        x.swim();
    }
    public static void f(Canfly x){
        x.fly();
    }
    public static void fi(ActionCharacter x) {
        x.fight();
    }
    public static void main(String[] args) {
        Hero hero=new Hero();
        s(hero);
        f(hero);
        fi(hero);
    }
}
interface Canswim{
    void swim();
}
interface Canfly{
    void fly();
}
class ActionCharacter{
    public void fight()
    {
        System.out.println("can fight!");
    }
}
class Hero extends ActionCharacter implements Canswim,Canfly{
    public void swim()
    {
        System.out.println("can swim!");
    }
    public void fly()
    {
        System.out.println("can fly!");
    }
}
接口只能由public和默认修饰
接口中的方法不能带有主体,因为其中的方法是抽象的
语法
    interface 接口名(){}
引用方法 class 类名 implements 接口名{……}
接口中的方法必须在接口其的类中实现,否则编译不通过
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值