OOP: Understand Class and Objects (2)

zhaozj2021-02-17  63

OOP: Understand Class and Objects (2)

[Author: Unknown Add Time: 2001-9-7 8:10:45]

{

Public Boolean IsamammmMal ()

{

Return (False);

}

Public boolean iscarnivorous ()

{

Return (False);

}

Public string getHello ()

{

Return ("QUACK");

}

}

After compiling and running our program, the output should be as follows:

A Dog Says Bark, IS Carnivors: True, IS A Mammal: True

A cat says meow, IS carnivous: true, is a mammal: TRUE

A Duck Says Quack, IS Carnivors: False, IS A Mammal: False

Look at our example, you will find that we define a new class called Animal, which defines three ways: isamammal, iscarnivorous, and gethello. You still noticed, we have the front of each existing class declaration Added an Extends Animal. This statement tells the compiler that these objects are subclasses of the Animal class.

Because ISAMMMAL and ISCARNIVOROUS return TRUE, Dog and CAT are not re-implement - the two methods of "overload". But the duck is neither a mammal is not a meat, so the DUCK class needs to be overloaded. Method to return the correct value. All of our objects say "Hello" in its own unique way, so they all need to overload the GetHello method. Because each animal says "Hello" is different, so we are in the base class The GetHello method is declared as abstraction, and we did not give this method a function. This forces animal to overload the GetHello method and define it according to the needs of each particular animal.

Because we declare the GetHello method as a virtual, we cannot directly instantiate animal objects. Therefore, we need to put the Animal class as abstraction. We add Abstract keywords to the start row defined in the Animal class. This is achieved. The ability to reload their base class is a polymorphism. Polymorphism allows subclasses to overload them when they use base classes or to overload them when they are insufficient. This realizes code reuse, accelerate code implementation Process, and it is also isolated and bugs in the program so that the maintenance of the program is easier.

to sum up

In this article, we have learned how to determine potential objects. We also learned how to use inheritance and polymorphism to speed up our code implementation process and isolate errors, which makes the code maintenance process easier. Next, we will discuss The concept of polymorphism and inheritance and starts our discussion of dynamic binding.

转载请注明原文地址:https://www.9cbs.com/read-30761.html

New Post(0)