Scjp test preparation-9

Source: Internet
Author: User

The execution result of the following code is as follows:

abstract class Vehicle{    public int speed(){        return 0;    }}class Car extends Vehicle{    public int speed(){        return 60;    }}class RacerCar extends Car{    public int speed(){        return 150;    }        public void run(){        System.out.println("I‘m running...");    }}public class Test{    public static void main(String[] args){        RacerCar racer = new RacerCar();        Car car = new RacerCar();         Vehicle vehicle = new RacerCar();         System.out.println(racer.speed() + ", " + car.speed()  + ", " + vehicle.speed());     }}

 

Analyze the question. Java polymorphism is examined in the question. For example, in the "car = new racercar ();" clause, the variable car is of the car type during compilation and is of the racercar type during runtime. In this case, when calling a method that references a variable at runtime, its method behavior always shows the characteristics of the subclass method, rather than the behavior characteristics of the parent class method, which may occur: variables of the same type call the same method and present different behavior characteristics. This is polymorphism.

It should be noted that the referenced variable can only call the method of its type during compilation, while the method of its runtime type is executed during execution. In the code above, if the car variable executes the run () method, it cannot be compiled because the car type does not have the run () method during compilation. Although the car variable points to an object, it does have the run () method (visible during reflection ).

Let's take a look at the execution result:

Scjp test preparation-9

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.