search
HomeJavajavaTutorialVariables in Java do not follow polymorphism and overriding
Variables in Java do not follow polymorphism and overridingSep 09, 2023 pm 06:13 PM
- Polymorphism- variables- rewrite

Variables in Java do not follow polymorphism and overriding

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!

Statement
This article is reproduced at:tutorialspoint. If there is any infringement, please contact admin@php.cn delete
Top 4 JavaScript Frameworks in 2025: React, Angular, Vue, SvelteTop 4 JavaScript Frameworks in 2025: React, Angular, Vue, SvelteMar 07, 2025 pm 06:09 PM

This article analyzes the top four JavaScript frameworks (React, Angular, Vue, Svelte) in 2025, comparing their performance, scalability, and future prospects. While all remain dominant due to strong communities and ecosystems, their relative popul

Spring Boot SnakeYAML 2.0 CVE-2022-1471 Issue FixedSpring Boot SnakeYAML 2.0 CVE-2022-1471 Issue FixedMar 07, 2025 pm 05:52 PM

This article addresses the CVE-2022-1471 vulnerability in SnakeYAML, a critical flaw allowing remote code execution. It details how upgrading Spring Boot applications to SnakeYAML 1.33 or later mitigates this risk, emphasizing that dependency updat

Node.js 20: Key Performance Boosts and New FeaturesNode.js 20: Key Performance Boosts and New FeaturesMar 07, 2025 pm 06:12 PM

Node.js 20 significantly enhances performance via V8 engine improvements, notably faster garbage collection and I/O. New features include better WebAssembly support and refined debugging tools, boosting developer productivity and application speed.

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

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

How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

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

How to Share Data Between Steps in CucumberHow to Share Data Between Steps in CucumberMar 07, 2025 pm 05:55 PM

This article explores methods for sharing data between Cucumber steps, comparing scenario context, global variables, argument passing, and data structures. It emphasizes best practices for maintainability, including concise context use, descriptive

How can I implement functional programming techniques in Java?How can I implement functional programming techniques in Java?Mar 11, 2025 pm 05:51 PM

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

Iceberg: The Future of Data Lake TablesIceberg: The Future of Data Lake TablesMar 07, 2025 pm 06:31 PM

Iceberg, an open table format for large analytical datasets, improves data lake performance and scalability. It addresses limitations of Parquet/ORC through internal metadata management, enabling efficient schema evolution, time travel, concurrent w

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.