Code example of inheritance problem in Java programming
Classroom exercises:
C in package bzu Aadefine a vehicle class in:
1. Attribute - capacity
2. Method
(1) Parameterless construction method (initialize capacity to 2 and output "execute parameterless construction method of vehicle class.")
(2) Parametric construction method (pass parameters to capacity initialization and output "execute parametric construction method of vehicle.")
(3) Set and get methods of capacity
(4) Print method: output capacity
C in package bzu Aadefine a car class (car) in the following to inherit the vehicle class:
1. Attribute - speed
2. Method
(1) Parameterless construction method (initialize speed to 0 and output "execute parameterless construction method of automobile class.")
(2) Parameterized construction method (use the super keyword to call the parameterized construction method of the parent class, pass the parameter to speed initialization, and output "execute the parameterized construction method of the automobile class.")
(3) Speed up: speed + 10 and return to speed;
(4) Speed down: speed-15 and return to speed;
(5) Override the print method: output speed and capacity.
C in package bzu BB defines a final bus class (bus), which inherits the car class:
1. Attribute - capacity < variable hiding >
2. Method
(1) Parameterless construction method (initialize capacity to 20 and output "execute parameterless construction method of bus class.")
(2) Parameterized construction method (use the super keyword to call the parameterized construction method of the parent class, pass the parameter to capacity initialization, and output "execute the parameterized construction method of the bus class.")
(3) Override the print method: output speed, capacity and the capacity of the parent class.
C in package bzu Write a main class test in BB:
1. Main function
(1) Call the parameterless construction method to create a car object car; call the acceleration method to increase the speed to 50 and call the print method; call the deceleration method to reduce the speed to 20 and call the print method.
(2) . call the parameterized construction method to create a bus object bus; call the print method##
Vehicle class:
Operation results:
summary
The above is all about the code example of Java programming inheritance in this paper. I hope it will be helpful to you. Interested friends continue to refer to this site: detailed explanation of Java Web applications using flow restriction to process a large number of concurrent requests, safe and unsafe code examples of Java threads, detailed explanation of list in Java collection, etc. if you have any questions, you can leave a message at any time, and the editor will reply to you in time. Thank you for your support!