继承笔记

Object.create(obj)创建了一个新对象,并指定了obj作为新对象的原型。

function Animal() { }
Animal.prototype = {
  constructor: Animal, 
  eat: function() {
    console.log("nom nom nom");
  }
};
let duck = Object.create(Animal.prototype); 
Animal.prototype.isPrototypeOf(duck) //true
duck instanceof(Animal) //true

function Animal() { }
Animal.prototype = {
  constructor: Animal,
  eat: function() {
    console.log("nom nom nom");
  }
};
function Dog() { }
Dog.prototype=Object.create(Animal.prototype)
let beagle = new Dog();
beagle.constructor===Dog // false
beagle.constructor===Animal //true
beagle.constructor===Animal.prototype.constructor //true
Dog.prototype.constructor===Animal //true

添加Dog.prototype.constructor=Dog;之后

function Animal() { }
Animal.prototype = {
  constructor: Animal,
  eat: function() {
    console.log("nom nom nom");
  }
};
function Dog() { };
Dog.prototype=Object.create(Animal.prototype);
Dog.prototype.constructor=Dog;
let beagle = new Dog();
beagle.constructor===Dog // true
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
继承是Java中的一种重要的面向对象编程概念,它允许一个类(子类)继承另一个类(父类)的属性和方法。通过继承,子类可以从父类中获得已有的属性和方法,并且可以在此基础上进行扩展或者修改。 在Java中,使用关键字"extends"来实现继承。子类通过继承父类,可以使用父类中的非私有属性和方法。子类可以直接访问父类的公有属性和方法,也可以通过super关键字来访问父类的构造方法和成员。 下面是一个简单的继承示例: ```java // 父类 class Animal { private String name; public Animal(String name) { this.name = name; } public void eat() { System.out.println(name + "正在吃饭"); } } // 子类 class Dog extends Animal { public Dog(String name) { super(name); } public void bark() { System.out.println("汪汪汪"); } } public class Main { public static void main(String[] args) { Dog dog = new Dog("旺财"); dog.eat(); // 调用父类的eat方法 dog.bark(); // 调用子类的bark方法 } } ``` 在上面的示例中,Animal类是父类,Dog类是子类。Dog类通过关键字"extends"继承了Animal类,从而可以使用Animal类中的属性和方法。在main方法中,我们创建了一个Dog对象,并调用了eat方法(来自父类)和bark方法(来自子类)。 通过继承,子类可以扩展父类的功能,并且可以在需要时覆盖父类的方法来实现特定的行为。继承是Java中实现代码重用和多态性的重要手段之一。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值