Computer Science

Java Polymorphism

Java Polymorphism is the ability of an object to take on many forms. It allows objects of different classes to be treated as if they were objects of the same class. This feature is achieved through method overriding and method overloading.

Written by Perlego with AI-assistance

11 Key excerpts on "Java Polymorphism"

  • AP Computer Science A Premium, 2024: 6 Practice Tests + Comprehensive Review + Online Practice
    UnderGrad .
    Polymorphism is the mechanism of selecting the appropriate method for a particular object in a class hierarchy. The correct method is chosen because, in Java, method calls are always determined by the type of the actual object, not the type of the object reference. For example, even though s, g , and u are all declared as type Student, s.computeGrade(), g.computeGrade() , and u.computeGrade() will all perform the correct operations for their particular instances. In Java, the selection of the correct method occurs during the run of the program.
    Here is a simple example. Now consider this hierarchy of classes, and the declarations that follow it:
    Suppose the Dog class has this method:
    public void eat() { /* implementation not shown */ }
    And each of the subclasses, Poodle, PitBull, Dachshund , etc., has a different, overridden eat method. Now suppose that allDogs is an ArrayList<Dog> where each Dog declared above has been added to the list. Each Dog in the list will be processed to eat by the following lines of code:
    Polymorphism is the process of selecting the correct eat method, during run time, for each of the different dogs.
    Recall that constructors are not inherited, and if you use the keyword super in writing a constructor for your subclass, the line containing it should precede any other code in the constructor.
    Recall also that if the superclass does not have a no-argument constructor, then you must write an explicit constructor for the subclass. If you don’t do this, later code that tries to create a subclass object will get a compile-time error. This is because the compiler will generate a default constructor for the subclass that tries to invoke the no-argument constructor of the superclass.

    Dynamic Binding (Late Binding)

    Making a run-time decision about which instance method to call is known as dynamic binding or late binding. Contrast this with selecting the correct method when methods are overloaded (see p. 106 ) rather than overridden. The compiler selects the correct overloaded method at compile time by comparing the methods’ signatures. This is known as static binding, or early binding. In polymorphism, the actual method that will be called is not determined by the compiler. Think of it this way: The compiler determines if a method can be called (i.e., does the method exist in the class of the reference?), while the run-time environment determines how
  • Learn Java 17 Programming
    getPermittedSubclasses() . The following is an example of their usage:
    Vehicle vehicle = new Vehicle("Ford", "Taurus", 300); System.out.println(vehicle.getClass().isSealed());                                                    //prints: true System.out.println(Arrays.stream(vehicle.getClass()                 .getPermittedSubclasses())                 .map(Objects::toString).toList());                              //prints list of permitted classes Car car = new Car("Ford", "Taurus", 300, 4); System.out.println(car.getClass().isSealed());  //prints: false System.out.println(car.getClass().getPermittedSubclasses());                                                  //prints: null
    The sealed interface integrates well with record because record is final and can be listed as a permittable implementation.

    Polymorphism in action

    Polymorphism is the most powerful and useful feature of OOP. It uses all the other OOP concepts and features we have presented so far. It is the highest conceptual point on the way to mastering Java programming. After discussing it, the rest of the book will be mostly about Java language syntax and JVM functionality.
    As we stated in the OOP concepts section, polymorphism is the ability of an object to behave as an object of different classes or as an implementation of different interfaces. If you search the word polymorphism on the internet, you will find that it is the condition of occurring in several different forms . Metamorphosis is a change of the form or nature of a thing or person into a completely different one, by natural or supernatural means . So, Java Polymorphism is the ability of an object to behave as if going through a metamorphosis and to exhibit completely different behaviors under different conditions.
    We will present this concept in a practical hands-on way, using an object factory – a specific programming implementation of a factory, which is a method that returns objects of a varying prototype or class (https://en.wikipedia.org/wiki/Factory_(object-oriented_programming ).

    The object factory

    The idea behind the object factory is to create a method that returns a new object of a certain type under certain conditions. For example, look at the CalcUsingAlg1 and CalcUsingAlg2
  • IT Interview Guide for Freshers
    eBook - ePub

    IT Interview Guide for Freshers

    Crack your IT interview with confidence

    Polymorphism is the feature of OOPs wherein an object can take multiple forms based on its type or class. The best example of polymorphism is invoking derived class functions through a base class reference at runtime. There are two types of polymorphism:
    • Static polymorphism also known as compile time polymorphism: Polymorphism that is resolved during the compiler time is known as static polymorphism. Method overloading is an example of compile time polymorphism. Method Overloading allows you to have more than one method having the same name, if the parameters of methods are different in number, sequence and data types of parameters.
    • Dynamic polymorphism also known as runtime polymorphism: Dynamic or runtime polymorphism is also known as method overriding in which a call to an overridden function is resolved during runtime, not at the compile time. It means having two or more methods with the same name, same signature but with different implementation.
    Figure 6.12: Different types of polymorphism

    Describe method overloading.

    Overloading is a OO concept that facilities declaring and defining several methods with the same name, but with different method signatures. Methods are identified based on:
    • Number of parameters
    • Types of parameters
    • Order of parameters
    Example: int addition(int a,int b) { return a+b;} int addition (int a,int b,int c) { return a+b+c;} float addition (float a, float b, float c) { return a+b+c;}

    In case the original method is non-static can we declare an overridden method to be static?

    The two virtual methods in the base and derived class must have the same method signatures.

    What is the significance of the virtual keyword ?

    A virtual keyword is leveraged while defining a class to mandate that the methods of the base class need to be overridden in the derived classes.

    What is a virtual function?

    A virtual function is a member function of a class, and its functionality can be overridden in its derived class. This function can be implemented using a keyword called virtual, and it can be given during function declaration. A virtual function can A token in C++, and it can be achieved in C Language using function pointers or pointers to function.
  • Learn Java 12 Programming
    eBook - ePub

    Learn Java 12 Programming

    A step-by-step guide to learning essential concepts in Java SE 10, 11, and 12

    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 as 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
    • Final variable, method, and class
    • Polymorphism in action
    Passage contains an image

    OOP concepts

    As we have already stated in the introduction, the main OOP concepts are as follows:
    • Object/Class : It defines a state (data) and behavior (methods) and holds them together
    • Inheritance : It propagates behavior down the chain of classes connected via parent-child relationships
    • Abstraction/Interface : It describes how the object data and behavior can be accessed. It isolates (abstracts) an object's appearance from its implementations (behavior)
    • Encapsulation : It hides the state and details of the implementation
    • Polymorphism : It allows an object to assume an appearance of implemented interfaces and behave as any of the ancestor classes
    Passage contains an image

    Object/class

    In principle, you can create a very powerful application with minimal usage of classes and objects. It became even easier to do this after functional programming was added to Java 8, to JDK, which allowed you to pass around behavior as a function. Yet passing data (state) still requires classes/objects. This means that the position of Java as an OOP language remains intact.
    A class defines the types of all internal object properties that hold the object state. A class also defines object behavior expressed by the code of the methods. It is possible to have a class/object without a state or without a behavior. Java also has a provision for making the behavior accessible statically—without creating an object. But these possibilities are no more than just additions to the object/class concept that was introduced for keeping the state and behavior together.
  • Object-Oriented Programming with ABAP Objects
    • James Wood, Joseph Rupert(Authors)
    • 2015(Publication Date)
    • SAP PRESS
      (Publisher)
    The term polymorphism literally means “many forms”. From an object-oriented perspective, polymorphism works in concert with inheritance to make it possible for various types within an inheritance tree to be used interchangeably. In this chapter, we’ll learn how to harness this power to create highly flexible program designs using ABAP Objects. 6 Polymorphism In the previous chapter, we learned how to define inheritance relationships between related classes. From there you will recall that the basic litmus test we used to identify these relationships was to ask ourselves whether or not a given class was a more specific type of a particular superclass. For example, a Dog is a specific type of Mammal. So, instead of creating a standalone Dog class, it makes sense to define the Dog class as a subclass of Mammal so that it can inherit selected features from Mammal. When we look at inheritance in this light, it’s easy to see its obvious benefits in terms of code reuse. However, as it turns out, there’s another (and arguably more important) dimension of the “is-a” relationship that we haven’t yet considered. Since the classes in an inheritance tree share a common public interface, it’s technically possible for a given subclass to respond to any request (i.e., method call) directed at its superclass. This aspect of the inheritance relationship is referred to as interface inheritance. When we combine interface inheritance with the ability for subclasses to redefine/override the implementation of their inherited methods, we end up in a situation where clients no longer have to worry about the types of objects they’re interfacing with: they simply issue requests (method calls) and let the objects themselves figure out how to process the requests in type-specific ways
  • Mastering JavaScript Object-Oriented Programming
    Support of polymorphism brings benefits in programming that go toward the overall goal of OOP. Mainly, it reduces coupling in our application, and in some cases, allows to create more compact code. The most common ways to support polymorphism with a programming language include:
    • Methods that take parameters with different data types (overloading)
    • Management of generic types, not known in advance (parametric polymorphism)
    • Expressions whose type can be represented by a class and classes derived from it (subtype polymorphism or inclusion polymorphism )
    In most languages, overloading is what happens when you have two methods with the same name but different signatures. At compile time, the compiler works out which method to call based on matching between types of invocation arguments and method's parameters. The following is an example of method overloading in C#:
    public int CountItems(int x) { return x.ToString().Length; } public int CountItems(string x) { return x.Length; }
    The CountItems() method has two signatures-one for integers and one for strings. This allows to count the number of digits in a number or the number of characters in a string in a uniform manner, just calling the same method.
    Overloading can also be expressed through methods with different numbers of arguments, as shown in the following C# example: public int Sum(int x, int y) { return Sum(x, y, 0); } public int Sum(int x, int y, int z) { return x+ y + z; }
    Here, we have the Sum() method that is able to sum two or three integers. The correct method definition will be detected on the basis of the number of arguments passed.
    As JavaScript developers, we are able to replicate this behavior in our scripts. For example, the C# CountItems()
  • Let Us C++
    eBook - ePub

    Let Us C++

    Dive into the nitty-gritties of C++ language and learn why programmers prefer OOPs and C++

    7

    Polymorphism

    After classes & objects and inheritance, polymorphism is the third important feature of C++. If you stop at inheritance, you will be missing out on the greatest part of the language, namely polymorphism. This chapter explains the polymorphism concept in detail.
    • Virtual Functions
    • Pure Virtual Functions
    • Abstract Class
    • Function Binding
    • Virtual Functions under the Hood
    • Why Use virtual Functions?
    • Object Slicing
    • Virtual Destructors Calling Virtual Functions from Ctors / Destructors
    • Virtual Base Classes
    • Exercise
    • KanNotes
     
    P rogrammers who switch over from C to C++ seem to do so in three steps. In the first step they start using C++ simply as “better C”. During this stage they start using function prototypes, scope resolution operator, const, references, and a few more small concepts. These don't have much to do with object oriented programming.
    Once comfortable with the non-object-oriented features of the language the second step is to use C++ as a “object-based” programming language. This means that they start appreciating the benefits of grouping data together with the functions that act upon it, the value of constructors and destructors, and perhaps some simple inheritance.
    Many programmers carry a wrong impression that since they have started using classes, objects and inheritance they have graduated to the object-oriented world. Though on the face of it everything may appear nice, neat and clean don't get fooled. The most important piece of C++ is polymorphism.
    In C++ polymorphism is encountered in two primary forms:
    1. One thing existing in several different forms
    2. One action leads to different activities
    We have already experienced the first form when we learnt overloaded functions and overloaded operators.
    In the second form, the action is ‘calling a function’ and activity that results from it is, different functions getting called in a class hierarchy. This form of polymorphism is implemented using virtual
  • Object-Orientation, Abstraction, and Data Structures Using Scala
    Implicit conversions are an advanced feature that you have been using all the time, but which are generally invisible to you. They make life easier by converting one type to another without forcing you to do any work. They can make it hard to tell what code is really doing in some places though, and for that reason, there are strict rules on what implicit conversions are allowed to happen. These include only using implicit conversions that are currently in scope, and not applying conversion transitively.

    4.4    End of Chapter Material

    4.4.1    Summary of Concepts
    • Polymorphic code is code that can work with many types. Universal polymorphism implies that it can work with an infinite number of types.
    • Inclusion polymorphism is a form of universal polymorphism that comes from subtyping. Scala, like most class -based object-oriented languages, gets this through inheritance.  
      – Subtypes cannot get direct access to private members of the supertype. The protected visibility is meant to address this, but it is not as secure as private because you have little control over what code might inherit from any class you write.
      – The super keyword refers to the part of the current object that holds the supertype and can be used to make calls on methods in the supertype that have been overridden in the current class .
      – In Scala, when a subtype overrides a method, the keyword override must come before the def keyword for the method declaration.
      – Anonymous classes are created when a call to new on a type is followed by a block of code.
      – Members and methods of a class can be left undefined. Such members are called abstract . If you have abstract members in a class , the class itself must be declared abstract. You cannot instantiate abstract classes .
      – A class can only inherit from one other class . There is a similar construct called a trait that allows for multiple inheritance. A trait is much like an abstract class .
      – Members and methods that should not be overridden can be declared final . You can also make whole class es final to prevent any other class es from extending them.
       
  • Data-Oriented Programming
    eBook - ePub

    Data-Oriented Programming

    Reduce software complexity

    • Yehonathan Sharvit(Author)
    • 2022(Publication Date)
    • Manning
      (Publisher)
    DAVE   I see. So an anthropomorphic book is a book where animals have human traits. The word sounds related to polymorphism.
      THEO   Absolutely. Polymorphism comes from the Greek polús, which means many, and morphe–, which, again, means form.
      DAVE   That makes sense. Polymorphism is the ability of different objects to implement the same method in different ways. That brings me back to my animal example. In OOP, I’d define an IAnimal interface with a greet method, and each animal class would implement greet in its own way. Here, I happen to have an example.
    Listing 13.1 OOP polymorphism illustrated with animals
    interface IAnimal { public void greet(); } class Dog implements IAnimal { private String name; public void greet() { System.out.println("Woof woof! My name is " + animal.name); } } class Cat implements IAnimal { private String name; public void greet() { System.out.println("Meow! I am " + animal.name); } } class Cow implements IAnimal { private String name; public void greet() { System.out.println("Moo! Call me " + animal.name); } }
      THEO   Let me challenge you a bit. What is the fundamental difference between OOP polymorphism and a switch statement?
      DAVE   What do you mean?
      THEO   I could, for instance, represent an animal with a map having two fields, name and type , and call a different piece of code, depending on the value of type .
    Theo pulls his laptop from its bag and fires it up. While the laptop is booting up, he enjoys another taste of that wonderful orange juice. When the laptop is ready, he quickly types in the example switch case. Meanwhile, Dave has finished his glass of orange juice.
  • Clojure in Action
    eBook - ePub
    • Amit Rathore(Author)
    • 2015(Publication Date)
    • Manning
      (Publisher)

    4.3. Summary

    We began this chapter by defining polymorphism as the ability to use multiple types as though they were the same—to substitute one type for another without changing code. We then distinguished three different kinds of polymorphism: parametric, ad hoc, and subtype. Parametric polymorphism is where the types aren’t mentioned at all; ad hoc is where multiple implementations name types explicitly but provide a parametric interface; subtype is where types are placed in a hierarchy so they can share implementations transparently.
    We then introduced multimethods in the context of ad hoc polymorphism and showed how they enable explicit mapping of types to implementations (via a dispatch function and value) but are still extensible with new types from the outside (called open dispatch). We then showed how you could dispatch with multiple different values at the same time (called multiple dispatch).
    We then discussed how multimethods have subtype polymorphism features as well because they allow you to build your own type hierarchies with derive that are matched with isa?. You were able to combine subtype polymorphism with multiple dispatch to eliminate duplicated code. But this introduced the possibility of dispatch values with ambiguous method implementations, but you were able to resolve these ambiguities using prefer-method. Finally, you saw that it’s possible for each multimethod to have its own independent type hierarchy.
    This chapter covered an interesting feature of Clojure, and using it in the right situation will make your programs richer. The next chapter will focus on another great capability of Clojure: seamless interoperability with Java code.
  • Java Professional Interview Guide
    eBook - ePub

    Java Professional Interview Guide

    Learn About Java Interview Questions and Practise Answering About Concurrency, JDBC, Exception Handling, Spring, and Hibernate

    Animal . This way, we can control the behavior of the subclass using the polymorphic reference.

    If Object is a cosmic superclass, what is wrong if you refer every object by it?

    Technically, there is nothing wrong in referring every object by the Object super class. But, this will create a very weird situation dynamically. Imagine the following statements:
    1. Object one=new Employee();
    2. Object two=new Car();
    3. Object three=new Student();
    Here, all the three objects are referred by the Object super class, which is perfectly fine for a compiler. But, when you try to invoke the methods of Employee, Car, or Students using the respective references, it will fail. The reason is quite obvious. Because all the objects are polymorphically referred, only those methods can be invoked that are known to the Object class.

    Can we extend more than one class?

    No, in Java, multiple inheritance is not supported. Though you can create hierarchical inheritance, you cannot create multiple inheritance.

    How do you achieve multiple inheritance in Java?

    The only way by which you can achieve multiple inheritance in Java is by using the concept of interfaces. You can create an interface and implement it in the class where you would like to have the multiple inheritance. Your class can extend one class, and it can implement any number of interfaces.

    Can you implement more than one interfaces?

    Yes, we can. One of the important reasons of using an interface is to achieve the cohesion effectively. You can implement more than one interface even if all the interfaces are not related with each other.
    The other thing that you can do is you can create relationships between the interfaces and use them as a hierarchal inheritance.
    Let us observe following code snippets for interfaces First and Second .
    First.java
    1. public interface First {
    2.   
      public void methodFirst ();
    3. }
    Second.java
    1. public interface Second extends First {
    2.   
      public void methodSecond ();
    3. }
    In the preceding snippet, interface Second is extended from First. You can extend one interface from another.
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.