Table of Contents
Polymorphism in Java
Example
Output
Rewriting in Java
Why don't variables follow polymorphism and overriding?
Variable coverage and variable hiding
in conclusion
Home Java javaTutorial Variables in Java do not follow polymorphism and overriding

Variables in Java do not follow polymorphism and overriding

Sep 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();
   }
}
Copy after login

Output

The cat meows
Copy after login

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);
   }
}
Copy after login

Output

The cat meows
The animal makes a sound
Copy after login

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 of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

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)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

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 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

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading? How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading? Mar 17, 2025 pm 05:43 PM

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]

How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution? How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution? Mar 17, 2025 pm 05:46 PM

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

How do I use Java's NIO (New Input/Output) API for non-blocking I/O? How do I use Java's NIO (New Input/Output) API for non-blocking I/O? Mar 11, 2025 pm 05:51 PM

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,

How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management? How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management? Mar 17, 2025 pm 05:45 PM

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

How do I use Java's sockets API for network communication? How do I use Java's sockets API for network communication? Mar 11, 2025 pm 05:53 PM

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

See all articles