继承

代码中创建的类,主要是为了抽象现实中的一些食物,有时候客观事物之间存在着一些关联关系,那么在表示类和对象的时候就存在一定的关联。
当我们发现一个类中的方法或属性有一定的关联关系时,我们就可以使用继承来达到代码重用的效果。
我们把被继承的类成为父类、基类或超类,需要继承的类我们成为子类、派生类。
基本的语法规则:
class 子类 extends 父类 {

}

  • 继承使用关键字extends
  • 在Java中一个子类只能继承一个父类
  • 子类会继承父类的所有public的字段和方法,对于父类的private的字段和方法,子类时无法访问的。
  • 子类的实例中,也包含父类的实例。可以使用super关键字得到父类实例的引用。

例:设计一个类来表示动物。

class Animal {
    public String name;
    public Animal(String name) {
        this.name = name;
   }
    public void eat(String food) {
        System.out.println(this.name + "正在吃" + food);
   }
}
class Cat extends Animal {
    public Cat(String name) {
        // 使用 super 调用父类的构造方法.必须放在第一行。
        super(name);
   }
}
class Bird extends Animal {
	public Bird(String name){
	 	super(name);
	}
 	public void fly() {
        System.out.println(this.name + "正在飞");
   }
}
public class Test {
    public static void main(String[] args) {
        Cat cat = new Cat("mimi");
        cat.eat("猫粮");
        Bird bird = new Bird("aa");
        bird.fly();
   }
}

1、protected关键字
如果我们把字段设为private,子类就不能访问了,但是设成public,又违背了“封装”的初衷。为了解决这两个矛盾,我们可以引入protected关键字。
对于类的调用者来说,protected修饰的字段和方法是不能被访问的。但是对于类的子类来说,是可以访问的。
我们可以将上面的代码进行修改。

public class Animal {
    protected String name;
    public Animal(String name){
     this.name = name;
   }
    public void eat(String food) {
        System.out.println(this.name + "正在吃" + food);
   }
}
public class Bird extends Animal {
    public Bird(String name) {
        super(name);
   }
    public void fly() {
        // 对于父类的 protected 字段, 子类可以正确访问
        System.out.println(this.name + "正在飞");
   }
}
public class TestDemo {
    public static void main(String[] args) {
        Animal animal = new Animal("小动物");
        System.out.println(animal.name); // 此时编译出错, 无法访问 name
   }
}

有时候我们会有更复杂的继承关系,可以使用同样的继承方式来实现多层继承,即子类还可以进一步的派生出新的子类。但是一般继承建议不要超过三层。

public Animal{

}
public Cat extends Animal{

}
public GardenCat extends Cat{

}

2、final关键字
final关键字可以修饰一个变量或者字段,表示常量。还可以修饰类,来表示被修饰的类不能被继承。

final public class Animal {
}
public class Bird extends Animal {
} 

此时就会编译出错。
final修饰的类被成为密封类,不能被继承。被final修饰的方法,成为密封方法
3、super关键字
super关键字代表父类对象的引用。
super():调用父类的引用
super.data():访问父类的属性
super.func():访问父类的成员方法

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值