为什么我需要创建一个类的引用,然后B级的对象

问题描述 投票:-1回答:2

我在编程新的,我观看YouTube视频教程(10:05-10:47)https://www.youtube.com/watch?v=ssAt_qrQpi0&index=31&list=PLsyeobzWxl7rooJFZhc3qPLwVROovGCfh,我不明白为什么我们会需要A级的参考和B类的对象?

从该视频科特林例如:VAR H:人类=异己()

从该视频的人H Java示例=新的外来()

的外来人和对象的参考

java kotlin
2个回答
1
投票

“人”与“异形”的使用是可怕在这里。相反,“人”,想到“动物”。而不是“外星人”,认为“狗”。

该术语也不算很好。 “对象”是字面对象本身:物理狗< - >与它在存储器中相关的位。 “参考”是变量,h。它引用的对象狗。 h不是“动物和狗的对象的参考”,作为视频与人/异己说。这是一个“参照Dog对象”。然而,可变“H”本身,它不会被迫只引用狗。事实上,它也可以引用任何动物。

例如,我可以写的代码:

Animal mypet = new Dog();
mypet = new Cat();

如果我写的行Dog mypet,那么我将不得不只写mypet = new Dog()mypet = getDogFromShelter(myNeighborhoodShelter)。它不会让我写mypet = new Cat()

猫很酷,所以这将是可怕的。因此,我们写Animal mypet允许可变mypet引用任何动物。 DogCatElephant将全部可用。然而,由于这个限制,我不能做任何具体Dog-东西mypet

如果mypet.bark()是动物mypet将无法正常工作。并非所有的动物可以吠叫。 mypet.eat(Food)会的工作,因为所有的动物可以吃了。如果我想我的宠物吠叫,因为我知道它是狗,现在的话,我可以做

((Dog)mypet)).bark(); // Will throw run-time error if mypet is not a Dog! // This is best to avoid, so just make mypet a Dog type if it must bark. // If you must make an Animal bark, use if (!(mypet instanceof Dog)) to handle the error propely.

这上面的代码将检查以确保mypet是让它前吠叫狗。

这可以在代码中写来实现

class Animal {
    int health = 100;
    void eat(Food f) {
        health += f.value;
    }
}

class Dog extends Animal { // States that "All Dogs are Animals"
    // The word "extends" allows you to write Animal a = new Dog();
    // "extends" also lets you do "Dog a = new Dog(); a.eat()"
    int health = 150; // Dogs are strong
    void bark() {
        scareNearbyAnimals();
    }
}

class Poodle extends Dog {
    // Both of these will work:
    // Dog mydog = new Poodle();
    // Animal mypet = new Poodle();
    int glamor = 50; // glamorous
}

视频混了对象VS参考,所以我会让它用下面的代码更明确

Dog a = new Dog(); b = a;

ab均引用同一个对象在此实例。如果Dog使用了大量的内存,那么b = a不会导致分配更多的内存。

b.hasEaten(); // False a.eat(); b.hasEaten(); // True b = new Dog(); // Now they are different. a does not affect b

a.eat()允许对象吃饭。在内存中的位改变:饥饿值已被重置。 b.hasEaten()会检查a当它是吃使用相同的狗的饥饿值。 b = new Dog()将它们分开,使ab引用不同的狗的对象。然后,他们将不再加上以前一样。


0
投票

好吧,让我解释一下。

我们要创建一流的人力的对象“人”假定“人”是人。 我们给人类的类中的一些功能,人类可以做到的。比方说,走,跑,坐下。 每个功能告诉对象(人)做什么。

在另一方面,我们要创建一个外国人来创建另一个对象的类。我们将其命名为“外星人”。假设外星人是一个人形,因此它可以为所欲为的人就可以了,再加上一些其他的特殊能力,人类不能。例如“飞”。

为了防止它来编写完全相同的功能(行走,奔跑,坐下)类外国人。我们继承类人,所以我们可以从世界级获得功能(行走,奔跑,坐下)。

所以我们说:人H - >对象“H”是一个人(OID)

但是,“H”,其实是一个陌生的,所以我们有那么总会有代码来定义它:

Human h = new Alien();

换一种说法。试想一下,你有这样的结构:

Human (functions: walk, run, sit)
 -- Alien (functions: (inherit: walk, run, sit), fly)

如果我错了请纠正我。

我希望帮助。

© www.soinside.com 2019 - 2024. All rights reserved.