Java基类构造

  

   什么是基类?在Java内很多个类可以有一个共同的起源——基类。

Base class constructors   - 2

   而这些类与基类的关系就是继承关系(Inherit)。许多个子类可以有一个共同的祖先。

public class Animal {

   String name;
   int age;
}

public class Cat extends Animal {

}

public class Dog extends Animal {

}

在这段代码中,我们使用了关键字entends来表示子类和基类的继承关系。在介绍继承的作用之前,我们需要知道子类和基类的调用顺序。

public class Animal {

   public Animal() {
       System.out.println("Animal constructor executed");
   }
}


public class Cat extends Animal {

   public Cat() {
       System.out.println("Cat constructor executed!");
   }

   public static void main(String[] args) {
       Cat cat = new Cat();
   }

Console output: Animal constructor executed

Cat constructor executed!

在这段代码中我们可以看到,当我们新建了一个Cat类之后,首先被调用的是基类Animal,接着才是Cat类。这样做的原因是防止重复的变量被子类和基类共享,比如所有动物都有大脑和心脏,但不是所有动物都有尾巴,对于大脑和心脏,我们可以在基类Animal当中声明,那么它的所有子类都能共享这两个变量,而对于尾巴来说,我们就可以在Cat类当中单独创建一个tail变量,从而不会影响其他子类以及基类。以下是代码展示。

public class Animal {

   String brain;
   String heart;

   public Animal(String brain, String heart) {
       this.brain = brain;
       this.heart = heart;
   }

public class Cat extends Animal {

   String tail;

   public Cat(String brain, String heart, String tail) {
       super(brain, heart);
       this.tail = tail;
   }

   public static void main(String[] args) {
       Cat cat = new Cat("Brain", "Heart", "Tail");
   }
}

在这段代码中,我们使用了super关键字,正如我们在上面提到的,在Java中,基类总是先被调用的所以可以用super来调用基类的构造方法。并且,对基类的调用一定要在对子类操作之前,否则将会出现错误。例如在Cat类的构造方法中,我们必须把super()放在第一句,如果调换两条语句的顺序,就会出现错误。

最后,我们还需要了解一个新的对象被创建时变量初始化的顺序

1.基类的Static变量

2.子类的Static变量

3.基类的非Static变量

4.基类构造器被调用

5.子类的非Static变量

6.子类构造器被调用

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值