In the world of object-oriented programming (OOP), polymorphism and rewriting are key concepts that bring flexibility and vitality to programming languages. Java, being a powerful OOP language, fully supports these features. However, it is crucial to understand that these characteristics apply to methods in Java and not to variables. In this article, we will explore why variables in Java do not follow polymorphism and overriding to gain a deeper understanding of Java's variable behavior.
Polymorphism in Java
Polymorphism is a Greek word meaning "many forms" and is a basic concept of OOP. It allows objects of different types to be treated as objects of a common supertype, allowing for more flexible and reusable code to be written. In Java, polymorphism is achieved through inheritance, interfaces, and method overriding.
Example
Let’s see an example
class Animal { void sound() { System.out.println("The animal makes a sound"); } } class Cat extends Animal { @Override void sound() { System.out.println("The cat meows"); } } public class Main { public static void main(String[] args) { Animal myAnimal = new Cat(); myAnimal.sound(); } }
Output
The cat meows
In this scenario, myAnimal is an Animal reference variable pointing to the Cat object. When the sound() method is called on myAnimal, the version in the Cat class is called, not the version in the Animal class. This is polymorphism, where the method to be called is determined by the actual object type, not the reference type.
Rewriting in Java
Method overriding is a specific form of polymorphism in Java, where a subclass provides a specific implementation of a method defined in its superclass. Methods in subclasses must have the same name, return type, and parameters as methods in the superclass.
Why don't variables follow polymorphism and overriding?
Why don't variables follow polymorphism and overriding? Unlike methods, variables in Java do not follow the concepts of polymorphism and overriding. This difference stems from fundamental differences in how methods and variables exist and operate in objects
In Java, instance variables belong to instances of a class, which means that each instance has its own copy of the instance variable. Therefore, changing the value of an instance variable in one object does not affect other objects of the same class.
Methods, on the other hand, belong to the class itself and not to any specific instance. This means that methods, unlike variables, do not have a separate copy for each object of the class.
Example
Let’s review the previous example, but this time add instance variables:
class Animal { String sound = "The animal makes a sound"; void makeSound() { System.out.println(sound); } } class Cat extends Animal { String sound = "The cat meows"; @Override void makeSound() { System.out.println(sound); } } public class Main { public static void main(String[] args) { Animal myAnimal = new Cat(); myAnimal.makeSound(); System.out.println(myAnimal.sound); } }
Output
The cat meows The animal makes a sound
In this code, myAnimal is an Animal reference pointing to the Cat object. The makeSound() method call on myAnimal will print "The cat meows", but the System.out.println(myAnimal.sound) line will print "The Animalmakes a sound". Why does this happen? Since the method follows polymorphism, the makeSound() method in the Cat class is executed. However, since variables do not follow polymorphism, the "sound variable" from the Animal class is used
This behavior is caused by the variable hiding principle. If a variable in a subclass has the same name as a variable in its superclass, the subclass variable hides the superclass variable
This does not mean that the superclass variable has been overridden. The two variables still exist independently, and the variable used is determined by the reference type, not the actual object type. That's why when we access the sound variable through Animal reference, we get the sound value from the Animal class instead of the Cat class.
Variable coverage and variable hiding
In Java, variables are not affected by overriding like methods. Instead, they follow the principle of variable hiding. There is a fundamental difference between variable hiding and method overriding:
Method Overriding - In overriding, a subclass provides a different implementation of a method that has been defined in its superclass. The decision of which method to call is based on the type of the actual object, rather than the reference type, which allows for polymorphism.
Variable Hiding - In variable hiding, if a variable in a subclass has the same name as a variable in its superclass, the subclass variable will hide the superclass variable. The decision of which variable to use is based on the reference type, not the type of the actual object.
These principles stem from the fact that methods represent behavior, while variables represent state. The behavior can be polymorphic and overridden, allowing different behaviors for different types of objects. In contrast, the state represented by a variable belongs to a specific instance and is not polymorphic.
in conclusion
In conclusion, understanding why variables in Java do not adhere to polymorphism and overriding can provide important insights into how Java works. This knowledge is essential for Java programmers to avoid misunderstandings and errors when using inheritance and polymorphism
The above is the detailed content of Variables in Java do not follow polymorphism and overriding. For more information, please follow other related articles on the PHP Chinese website!

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

This article explores integrating functional programming into Java using lambda expressions, Streams API, method references, and Optional. It highlights benefits like improved code readability and maintainability through conciseness and immutability

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

This article explains Java's NIO API for non-blocking I/O, using Selectors and Channels to handle multiple connections efficiently with a single thread. It details the process, benefits (scalability, performance), and potential pitfalls (complexity,

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

This article details Java's socket API for network communication, covering client-server setup, data handling, and crucial considerations like resource management, error handling, and security. It also explores performance optimization techniques, i


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Dreamweaver CS6
Visual web development tools

WebStorm Mac version
Useful JavaScript development tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.