Computer Science

Java Method Overriding

Java Method Overriding is a feature in object-oriented programming that allows a subclass to provide a specific implementation of a method that is already provided by its parent class. The method in the subclass must have the same name, parameters, and return type as the method in the parent class. This allows for more flexibility and customization in the behavior of objects.

Written by Perlego with AI-assistance

7 Key excerpts on "Java Method Overriding"

  • Book cover image for: The Java Workshop
    No longer available |Learn more

    The Java Workshop

    A Practical, No-Nonsense Introduction to Java Development

    • David Cuartielles, Andreas Göransson, Eric Foster-Johnson(Authors)
    • 2019(Publication Date)
    • Packt Publishing
      (Publisher)
    Tablet , but they have been cleaned up so as not to make the example programs too long.
    class Computer {     public void whatIsIt() {         System.out.println( "it is a PC");     } } class Tablet extends Computer {     public void whatIsIt() {         System.out.println( "it is a tablet");     } } class Example06 {     public static void main(String[] args) {         Tablet myTab = new Tablet();         myTab.whatIsIt();     } }
    Since Tablet extends Computer , you could modify the main class in the program to be as follows:
    class Example06 {     public static void main(String[] args) {         Computer myTab = new Tablet();         myTab.whatIsIt();     } }
    Technically, tablets are computers, which means that you can create an object of the Tablet class by defining it as Computer in the first place. The result for both cases will be the same:
    it is a tablet Process finished with exit code 0
    The result is the same for both classes because both the child and parent classes include a non-static method called whatIsIt() . When calling the method, the overriding one will have priority. This is done by the JVM at runtime. This principle is what we call runtime polymorphism. There can be multiple definitions of the same method, and which definition will be executed is decided during the execution of the program.
    But what would happen if the method you called was static? This could be a design decision taken by the developer who is creating the class you are extending and therefore is a situation out of your control. In this case, it is not possible to override the method. The child class can, however, hide the method defined by the parent using the same mechanism. The next code listing demonstrates this.
  • Book cover image for: Data Structures
    eBook - PDF

    Data Structures

    Abstraction and Design Using Java

    • Elliot B. Koffman, Paul A. T. Wolfgang(Authors)
    • 2021(Publication Date)
    • Wiley
      (Publisher)
    1.3 Method Overriding, Method Overloading, and Polymorphism 17 Polymorphism An important advantage of OOP is that it supports a feature called polymorphism, which means many forms or many shapes. Polymorphism enables the JVM to determine at run time which of the classes in a hierarchy is referenced by a superclass variable or parameter. Next, we will see how this simplifies the programming process. Suppose you are not sure whether a computer referenced in a program will be a notebook or a regular computer. If you declare the reference variable Computer theComputer; you can use it to reference an object of either type because a type Notebook object can be referenced by a type Computer variable. In Java, a variable of a superclass type (general) can reference an object of a subclass type (specific). Notebook objects are Computer objects with more features. When the following statements are executed, theComputer = new Computer("Acme", "Intel", 2, 160, 2.6); System.out.println(theComputer.toString()); you would see four output lines, representing the state of the object referenced by theComputer. Now suppose you have purchased a notebook computer instead. What happens when the following statements are executed? theComputer = new Notebook("Bravo", "Intel", 4, 240, 2.4. 15.0, 7.5); System.out.println(theComputer.toString()); Recall that theComputer is type Computer. Will the theComputer.toString() method call return a string with all seven data fields or just the five data fields defined for a Computer object? The answer is a string with all seven data fields. The reason is that the type of the object receiving the toString message determines which toString method is called. Even though variable theComputer is type Computer, it references a type Notebook object, and the Notebook object receives the toString message. Therefore, the method toString for class Notebook is the one called.
  • Book cover image for: Java Fundamentals
    No longer available |Learn more

    Java Fundamentals

    A fast-paced and pragmatic introduction to one of the world's most popular programming languages

    • Gazihan Alankus, Rogério Theodoro de Brito, Basheer Ahamed Fazal, Vinicius Isola, Miles Obare(Authors)
    • 2019(Publication Date)
    • Packt Publishing
      (Publisher)
    Student class:
    public class Student extends Person { …. public void walk(int speed){ //Walk to class System.out.println("Walking to class .."); } …... }
    When we call student.walk(20) , this method in our Student class will be called instead of the same method in the Person class. That is, we have provided a unique way to walk for our Student class that isn't the same for the Lecturer and Person classes.
    In Java, we refer to such a method as overridden and the process as method overriding. The Java virtual machine (JVM) calls the appropriate method for the object that is referred.

    The Difference between Overriding and Overloading

    Let's have a look at the difference between method overloading and overriding:
    • Method overloading deals with the notion of having two or more methods in the same class with the same name but different arguments:void foo(int a) void foo(int a, float b)
    • Method overriding means having two methods with the same arguments, but different implementations. One of them would exist in the parent class, while another would exist in the child class:class Parent { void foo(double d) { // do something } } class Child extends Parent { void foo(double d){ // this method is overridden. } }

    Annotations

    We will now cover another important topic that will help us write better Java programs.
    Annotations are a way in which we can add metadata to our programs. This metadata can include information such as the version of a class we are developing. This is useful in scenarios where a class is deprecated or where we are overriding a certain method. Such metadata is not part of the program itself, but can help us catch errors or offer guidance. Annotations have no direct effect on the operation of the code they annotate.
    Let's look at a scenario. How do we ensure that we are overriding a certain method and not creating another completely different method? When overriding a method, a single mistake such as using a different return type will cause the method to not be overridden anymore. Such a mistake is easy to make but can lead to software bugs later on if not taken care of early in the software development stages. How, then, do we enforce overriding? The answer, as you might have already guessed, is using annotations.
  • Book cover image for: Java Programming
    eBook - PDF
    Copyright 2019 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it. 503 Chapter Summary Chapter Summary • In Java, inheritance is a mechanism that enables one class to inherit both the behavior and the attributes of another class. Using inheritance saves time because the original fields and methods already exist, have been tested, and are familiar to users. A class that is used as a basis for inheritance is a base class. A class you create that inherits from a base class is called a derived class. You can use the terms superclass and subclass as synonyms for base class and derived class; you also can use the terms parent class and child class. • You use the keyword extends to achieve inheritance in Java. A parent class object does not have access to its child’s data and methods, but when you create a subclass by extending an existing class, the new subclass contains data and methods that were defined in the original superclass. • Polymorphism is the act of using the same method name to indicate different implementations for methods based on the type of object. You use polymorphism when you override a superclass method in a subclass by creating a method with the same name and parameter list. • When you create any subclass object, the superclass constructor must execute first, and then the subclass constructor executes. When a superclass contains only constructors that require arguments, you must include at least one constructor for each subclass you create.
  • Book cover image for: C# For Java Programmers
    • Harold Cabrera(Author)
    • 2002(Publication Date)
    • Syngress
      (Publisher)
    234 Chapter 6 • Object-Oriented Programming The virtual Modifier When multiple classes in a hierarchy implement similar methods it can be con-fusing determining which method is actually invoked by any particular call. C# handles these polymorphic methods quite a bit differently than Java. Consider the Java class hierarchy in Figure 6.7. In the class hierarchy of Figure 6.7 we have a base class A and two derived classes B and C. Using polymorphism we could create objects of all three types and refer to them using baseclass or A references.What happens if you have an A reference to a C object and you use the A reference to call the foo() method? Let’s look at the following Java code to see what happens. Java Object-Oriented Programming • Chapter 6 235 236 Chapter 6 • Object-Oriented Programming Output Object-Oriented Programming • Chapter 6 237 The override Modifier Whenever you use the virtual or abstract modifier in a base class method, the matching methods in derived classes must use either the override or new modifier. The purpose of the override modifier is to indicate that the derived class version of the method overrides the base class implementation. In Java this is the default behavior. In the Acme Widgets Inc. hierarchy all of the GetGrossPay methods in the derived classes should be declared override .The declaration is as follows: 238 Chapter 6 • Object-Oriented Programming Object-Oriented Programming • Chapter 6 239 240 Chapter 6 • Object-Oriented Programming The abstract or virtual modifiers combined with override give you a powerful mechanism for customization within a class hierarchy. In the Acme Widgets Inc. hierarchy, the abstract GetGrossPay method requires that all the specialized employee types provide their own GetGrossPay method. It is a perfect fit for our hierarchy since each employee class has its own way of computing gross pay.
  • Book cover image for: Learn Java 17 Programming
    superclass .
    Another form of relationship was defined between classes and interfaces – a class can implement an interface. Since an interface describes how you can interact with an object but not how an object responds to the interaction, different objects can behave differently while implementing the same interface.
    In Java, a class can have only one direct parent but can implement many interfaces.
    The ability to behave like any of its ancestors and adhere to multiple interfaces is called polymorphism .
    In this chapter, we will look at these OOP concepts and how they are implemented in Java. The topics discussed include the following:
    • OOP concepts
    • Class
    • Interface
    • Overloading, overriding, and hiding
    • The final variable, method, and class
    • Record and sealed classes
    • Polymorphism in action

    Technical requirements

    To be able to execute the code examples provided in this chapter, you will need the following:
    • A computer with a Microsoft Windows, Apple macOS, or Linux operating system
    • Java SE version 17 or later
    • An IDE or code editor that you prefer
    The instructions for how to set up a Java SE and IntelliJ IDEA editor were provided in Chapter 1 , Getting Started with Java 17 , of this book. The files with the code examples for this chapter are available in the GitHub repository at https://github.com/PacktPublishing/Learn-Java-17-Programming.git in the examples/src/main/java/com/packt/learnjava/ch02_oop
  • Book cover image for: An Object-Oriented Approach to Programming Logic and Design
    Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it. Purists find a subtle difference between overloading and polymorphism. Some reserve the term poly-morphism (or pure polymorphism ) for situations in which one method body is used with a variety of arguments. For example, a single method that can be used with any type of object is polymorphic. The term overloading is applied to situations in which you define multiple methods with a single name (for example, three methods, all named display() , that display a number, an employee, and a student, respectively). Certainly, the two terms are related; both refer to the ability to use a single name to communicate multiple meanings. For now, think of overloading as a primitive type of polymorphism. Inheritance Another important concept in object-oriented programming is inheritance , which is the process of acquiring the traits of one ’ s predecessors. In the real world, a new door with a stained glass window inherits most of its traits from a standard door. It has the same purpose, it opens and closes in the same way, and it has the same knob and hinges. As Figure 7-3 shows, the door with the stained glass window simply has one additional trait — its window. Even if you have never seen a door with a stained glass window, you know what it is and how to use it because you understand the characteristics of all doors. With object-oriented programming, once you create an object, you can develop new objects that possess all the traits of the original object plus any new traits you desire. If you develop a CustomerBill class of objects, there is no need to develop an OverdueCustomerBill class from scratch. You can create the new class to contain all the characteristics of the already developed one, and simply add necessary new characteristics.
Index pages curate the most relevant extracts from our library of academic textbooks. They’ve been created using an in-house natural language model (NLM), each adding context and meaning to key research topics.