In object-oriented programming, Java's polymorphism is a powerful feature that allows objects to exhibit flexible and changeable behavior. Through polymorphism, the same method can show different behaviors according to different object types, which brings great convenience to the flexibility and scalability of the code. In this article, PHP editor Xinyi will reveal the secret weapon of Java polymorphism and take you to have an in-depth understanding of this important programming concept so that it can be better applied in actual development.
1. Inheritance to achieve polymorphism
In Java, inheritance is the most common way to achieve polymorphism. When a class is derived from another class, the child class inherits all the properties and methods of the parent class. In addition, subclasses can also define their own properties and methods, thereby extending the functionality of the parent class.
Demo code:
class Animal { public void eat() { System.out.println("Animal is eating"); } } class Dog extends Animal { @Override public void eat() { System.out.println("Dog is eating"); } } public class Main { public static void main(String[] args) { Animal animal = new Dog(); animal.eat(); // 输出:Dog is eating } }
In this example, theDog
class inherits from theAnimal
class and overrides theeat()
method. When we create aDog
object and assign it to aAnimal
variable, we can call theeat()
method, but what is actually executed is ## Theeat()
method in the #Dogclass.
2. Interface implementation polymorphism
In Java, interfaces are also an important way to achieve polymorphism. An interface is a collection of methods that defines the behavior of an object, but does not define the state of the object. When a class implements an interface, it must implement all methods defined in the interface.Demo code:
interface Drawable { void draw(); } class Rectangle implements Drawable { @Override public void draw() { System.out.println("Drawing a rectangle"); } } class Circle implements Drawable { @Override public void draw() { System.out.println("Drawing a circle"); } } public class Main { public static void main(String[] args) { Drawable drawable = new Rectangle(); drawable.draw(); // 输出:Drawing a rectangle drawable = new Circle(); drawable.draw(); // 输出:Drawing a circle } }
Drawableinterface defines a
draw()method, and both the
Rectangleand
Circleclasses implement this interface. When we create a
Drawableobject and assign it to a
Rectangleor
Circlevariable, we can call the
draw()method, But what is actually executed is the
draw()method in the
Rectangleor
Circleclass.
3. Benefits of polymorphism
Polymorphism brings many benefits to Java, including:The above is the detailed content of Java polymorphism: the secret weapon that makes objects flexible and changeable. For more information, please follow other related articles on the PHP Chinese website!