slug
type
status
category
summary
date
tags
password
icon
1. Creating Superclasses and Subclasses
Inheritance allows a class to inherit properties and methods from another class. Here's a basic example:
Explanation:
Dog
inherits the eat()
method from Animal
. The main
method creates an instance of Dog
and calls both the inherited eat()
method and its own display()
method.2. Writing Constructors for Subclasses
Constructors in subclasses can access parent class constructors using
super()
:Explanation: The
Dog
constructor calls the Animal
constructor first, ensuring the superclass is initialized before the subclass.3. Overriding Methods
Subclasses can modify inherited methods, a process known as overriding:
Explanation:
Dog
overrides the eat()
method of Animal
, changing the behavior when an instance of Dog
calls eat()
.4. Using Inheritance Hierarchies
Java supports creating a hierarchy of inheritance:
Explanation: This example shows a three-level hierarchy where
Dog
inherits methods from Mammal
, and Mammal
inherits from Animal
.5. Polymorphism
Polymorphism allows methods to perform differently based on the object that calls them:
Explanation: Depending on whether
myAnimal
references a Dog
or Cat
object, the sound()
method behaves differently, showcasing polymorphism.These examples provide a foundational understanding of how inheritance works in Java, demonstrating essential object-oriented programming techniques like constructors, method overriding, and polymorphism within class hierarchies.
- 作者:现代数学启蒙
- 链接:https://www.math1234567.com/csa002
- 声明:本文采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处。
相关文章