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
Related key terms
1 of 5
12 Key excerpts on "Java Polymorphism"
- No longer available |Learn more
- (Author)
- 2014(Publication Date)
- Learning Press(Publisher)
________________________ WORLD TECHNOLOGIES ________________________ Chapter 3 Type Polymorphism and Type System Type polymorphism In computer science, polymorphism is a programming language feature that allows values of different data types to be handled using a uniform interface. The concept of parametric polymorphism applies to both data types and functions. A function that can evaluate to or be applied to values of different types is known as a polymorphic function. A data type that can appear to be of a generalized type (e.g., a list with elements of arbitrary type) is designated polymorphic data type like the generalized type from which such specializations are made. There are two fundamentally different kinds of polymorphism, originally informally described by Christopher Strachey in 1967. If the function denotes different and potentially heterogeneous implementations depending on a limited range of individually specified types and combinations, it is called ad-hoc polymorphism . Ad-hoc poly-morphism is supported in many languages using function and method overloading. If all code is written without mention of any specific type and thus can be used transparently with any number of new types, it is called parametric polymorphism . John C. Reynolds (and later Jean-Yves Girard) formally developed this notion of polymorphism as an extension to the lambda calculus (called the polymorphic lambda calculus, or System F). Parametric polymorphism is widely supported in statically typed functional programming languages. In the object-oriented programming community, programming using parametric polymorphism is often called generic programming . In object-oriented programming, inclusion polymorphism is a concept in type theory wherein a name may denote instances of many different classes as long as they are related by some common super class. - No longer available |Learn more
- (Author)
- 2014(Publication Date)
- College Publishing House(Publisher)
________________________ WORLD TECHNOLOGIES ________________________ Chapter 9 Type Polymorphism and Type System Type polymorphism In computer science, polymorphism is a programming language feature that allows values of different data types to be handled using a uniform interface. The concept of parametric polymorphism applies to both data types and functions. A function that can evaluate to or be applied to values of different types is known as a polymorphic function. A data type that can appear to be of a generalized type (e.g., a list with elements of arbitrary type) is designated polymorphic data type like the generalized type from which such specializations are made. There are two fundamentally different kinds of polymorphism, originally informally described by Christopher Strachey in 1967. If the function denotes different and potentially heterogeneous implementations depending on a limited range of individually specified types and combinations, it is called ad-hoc polymorphism . Ad-hoc poly-morphism is supported in many languages using function and method overloading. If all code is written without mention of any specific type and thus can be used transparently with any number of new types, it is called parametric polymorphism . John C. Reynolds (and later Jean-Yves Girard) formally developed this notion of polymorphism as an extension to the lambda calculus (called the polymorphic lambda calculus, or System F). Parametric polymorphism is widely supported in statically typed functional programming languages. In the object-oriented programming community, programming using parametric polymorphism is often called generic programming . In object-oriented programming, inclusion polymorphism is a concept in type theory wherein a name may denote instances of many different classes as long as they are related by some common super class. - eBook - ePub
- Yuan Dong, Fang Yang, Li Zheng(Authors)
- 2019(Publication Date)
- De Gruyter(Publisher)
8PolymorphismThe power of object-oriented programming lies not only in inheritance, but also in its ability to treat a derived-class object like a base-class object. It is polymorphism and dynamic binding that support this mechanism.8.1An Overview of Polymorphism
Polymorphism means that different objects behave differently when they are given the same message. The call by member functions is the ‘message’ and different behaviors are due to different implementations, i.e., calling different functions. Polymorphism is quite often used in programming. The most common example is the math operator. We use the same plus sign “+” to implement adding operation between integers, floating numbers, and double precision floating numbers. The same message, adding, is accepted by different objects or variables, and different variables carry out the adding operation in different ways. If the adding operation is performed on variables of different types, e.g., a floating and an integer, then the integer will first be converted to a floating point before adding. This is a typical polymorphism.8.1.1Types of Polymorphism
Object-oriented polymorphism can be divided into four types: overload polymorphism, coercion polymorphism, inclusion polymorphism, and argument polymorphism. The former two fall into the category of special polymorphism, while the latter two, general polymorphism. Overloads of ordinary functions and overloads of class member functions are both overload polymorphism. We will learn operator overloading in this chapter. The example of the add operation between floating numbers and integers is an example of overload. Coercion polymorphism is converting the type of a variable to meet the requirement of the function or operation. When adding a floating number and an integer, first we should do type coercion to convert an integer to a floating number. This is an example of coercion polymorphism. - 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. - eBook - PDF
Computer Programming NQF4 Student's Book
TVET FIRST
- S Sasti D Sasti(Author)
- 2020(Publication Date)
- Troupant(Publisher)
There are two types of polymorphism: l Static (early binding): ¢ Occurs during compile time when developers debug their code. ¢ Overloading implements early binding and the methods can be in the same class or different classes. ¢ We use the keyword Overloads to change the behaviour of the inherited method. ¢ A class can have several implementations, or overloads, of the same method that differ in the number of parameters or parameter types. Overloading: Refers to creating many methods with the same name but with different parameter lists. Overriding: Refers to the use of two methods with the same name and parameter list but each method must perform different sets of tasks. 13 Module 1 ¢ When the application is linked and compiled, each call to a method is linked to the address of that method stored in the computer’s memory. l Dynamic (late binding) ¢ Occurs during runtime when the application is executed and running. ¢ Overriding implements late binding and one method must be in the parent class with the other method in the child class. Both methods cannot be in the same class. ¢ We implement overriding when we want to use two methods with the same name and parameter list but each method must perform different sets of tasks. ¢ The link to the address of the method is only assigned during runtime. Polymorphism in use Refer to Figure 1.7 as we take a look at how polymorphism works. The program in Figure 1.7 implements both overloading and overriding polymorphism: l Demonstrating overloading: ¢ Child classes are clsDog and clsBird . Both use overloaded constructors New() . One constructor has no parameters while the other has two parameters. l Demonstrating overriding: ¢ The parent class clsAnimal has a method Move( ) which both child classes will inherit because of inheritance. ¢ The method Move( ) is overridden by both child classes clsDog and clsBird to perform differently. - eBook - ePub
- 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 - eBook - PDF
- Andrew W. Appel, Jens Palsberg(Authors)
- 2002(Publication Date)
- Cambridge University Press(Publisher)
16 Polymorphic Types poly-mor-phic: able to assume different forms Webster’s Dictionary Some functions execute in a way that’s independent of the data type on which they operate. Some data structures are structured in the same way regardless of the types of their elements. As an example, consider a function to concatenate linked lists in Java. We define a List class, subclasses for empty and nonempty lists, and a (nonde- structive) append method: abstract class IntList { IntList append(IntList more); } class IntCons extends IntList { Integer head; IntList tail; IntCons (Integer head, IntList tail) { this.head=head; this.tail=tail; } IntList append(IntList more) { return new IntCons(head, tail.append(more)); } } class IntNull extends IntList { IntNull () {} IntList append(IntList more) { return more; } } There’s nothing about the code for the IntList data type or the append method that would be any different if the element type were String or Tree instead of Integer. We might like append to be able to work on any kind of 335 CHAPTER SIXTEEN. POLYMORPHIC TYPES list. We could, of course, use the word Object instead of Integer to declare head, but then if we unintentionally mixed Integers and Strings as elements of the same List, the compiler’s type-checker wouldn’t be able to give us useful feedback: we’d get a runtime exception at a downcast somewhere. A function is polymorphic (from the Greek many+shape) if it can operate on arguments of different types. There are two main kinds of polymorphism Parametric polymorphism. A function is parametrically polymorphic if it fol- lows the same algorithm regardless of the type of its argument. The Ada or Modula-3 generic mechanism, C++ templates, or ML type schemes are exam- ples of parametric polymorphism. Overloading. A function identifier is overloaded if it stands for different algo- rithms depending on the type of its argument. - eBook - PDF
- Michael T. Goodrich, Roberto Tamassia, David M. Mount(Authors)
- 2011(Publication Date)
- Wiley(Publisher)
A pointer variable p that points to a class object that has at least one virtual function is said to be polymorphic. That is, p can take many forms, depending on the specific class of the object it is referring to. This kind of functionality allows a specialized class T to extend a class S, inherit the “generic” functions from class S, and redefine other functions from class S to account for specific properties of objects of class T. Inheritance, polymorphism, and function overloading support reusable soft- ware. We can define classes that inherit generic member variables and functions and can then define new, more specific variables and functions that deal with spe- cial aspects of objects of the new class. For example, suppose that we defined a generic class Person and then derived three classes Student, Administrator, and Instructor. We could store pointers to all these objects in a list of type Person*. When we invoke a virtual member function, such as print, to any element of the list, it will call the function appropriate to the individual element’s type. Specialization There are two primary ways of using inheritance, one of which is specialization. In using specialization, we are specializing a general class to a particular derived class. Such derived classes typically possess an “is a” relationship to their base class. The derived classes inherit all the members of the base class. For each inherited function, if that function operates correctly, independent of whether it is operating for a specialization, no additional work is needed. If, on the other 2.2. Inheritance and Polymorphism 79 hand, a general function of the base class would not work correctly on the derived class, then we should override the function to have the correct functionality for the derived class. For example, we could have a general class, Dog, which has a function drink and a function sniff. - eBook - PDF
- Kenneth Barclay, John Savage(Authors)
- 2003(Publication Date)
- Butterworth-Heinemann(Publisher)
Polymorphic substitution allows any class of object to be supplied as the actual parameter. This is a common strategy used with Java to develop generally reusable (generic) methods. For example, the add method advertised by a collection declares its formal parameter to be an Object and so any class of object to be added to it (see appendix E). The default behaviour for equals that compares objects by identity is not always what is required. In fact it can sometimes be confusing as the following code illustrates: // Create two distinct objects Employee e1 = new Employee(123, 2000, “John”); Employee e2 = new Employee(123, 2000, “John”); // if (e1.equals(e2) ) ConsoleIO.out.println(“Equal”); else ConsoleIO.out.println(“Not equal”); It produces Not equal as its output even though we might believe that the two Employee s are clearly equal. Usually we expect two objects to be considered equal if they have one or more equal attribute values. For example, two distinct Employee objects with the same payroll number are equal in this sense. To make this possible we redefine the method for equals (inherited from Object ) and use the polymorphic effect. If we introduce: // class Employee public final int getPayrollNumber() { return thePayrollNumber; } // method: getPayrollNumber Chapter 5: Specialization 147 to the Employee class we might have: // class Employee public final int compareTo(Object obj) { Employee emp = (Employee)obj; return thePayrollNumber - emp.getPayrollNumber(); } // method: compareTo public final boolean equals(Object obj) { return this .compareTo(obj) == 0; } // method: equals Now two Employee s are equal if they have the same payroll number and the previous code sample produces the output Equal as expected. For more discussion on the method equals see section 5.9 and appendix E. - Mark C. Lewis, Lisa Lacher, Lisa L. Lacher(Authors)
- 2017(Publication Date)
- Chapman and Hall/CRC(Publisher)
Chapter 4Abstraction and Polymorphism
4.1 Polymorphism 4.2 Inclusion Polymorphism (Inheritance and Subtyping) Why Supertypes Do Not Know About Subtypes 4.2.1 Inheritance in the Scala Type System 4.2.2 Inheritance in Scala Code Arguments to the Supertype4.2.3 private Visibility and Inheritancen4.2.4 protected Visibility4.2.5 Calling Methods on the Supertype 4.2.6 Abstract ClassesWhy Require override ?4.2.7 traitstrait or abstract class ?4.2.8 final4.2.9 Method Resolution Why Linearize? 4.2.10 Inheriting from Function Types Scala Applications Revisited 4.2.11 Enumerations 4.3 Parametric Polymorphism 4.3.1 Parametric Types 4.3.2 Parametric Functions and Methods 4.3.2.1 Parametric Sorts Comparators 4.3.3 Type Bounds Covariant and Contravariant 4.3.3.1 Type Bounds and Sorting 4.4 End of Chapter Material 4.4.1 Summary of Concepts 4.4.2 Exercises 4.4.3 ProjectsUnderstanding the concept of abstraction is critical for improving your capabilities as a programmer. The ability to express our thoughts in more abstract ways is a significant part of what has allowed modern software systems to scale to the size they are today. Abstraction comes in many forms, and you have dealt a little with abstraction already. At the simplest level, writing a function or a method that takes arguments is a form of abstraction. The one function can work for as many values as you want. Consider the basic example of a function that squares numbers. You can write the code 3 * 3 or 5 * 5 , but a function like the following is an abstract representation of that procedure for the Double type.def square(x: Double): Double = x * xA more interesting form of abstraction that we already know enough to create is writing methods that take functions as arguments. A simple example of that would be a method that reads values from input and combines them in various ways as specified by the calling code. To understand this, consider the following two methods.- eBook - PDF
- Arvind Kumar Bansal(Author)
- 2013(Publication Date)
- Chapman and Hall/CRC(Publisher)
Inclusion polymorphism is supported through the use of inheritance. A subclass inher-its the definitions of the parent class and can use the member-entities. Subclass allows “override” in addition to inheritance because a virtual method can redefine a method. Different subclasses redefine the virtual methods thus overloading the method name. 11.4.1 Parametric Polymorphism and Generic Templates Generic methods use a generic declaration utilizing type-variables . A type-variable is instantiated with a specific type at the time of invocation, and the method becomes specific to the type passed as parameter. A general abstract syntax for generic method in C ++ using template construct is illustrated in Examples 11.5, 11.6 and Figure 11.5. Similarly Ada, Java, and C# support parametric polymorphism through the use of generic methods. Example 11.6 illustrates the use of generic methods in C#. Example 11.5 The following code illustrates parametric polymorphism through template dec-laration. The variable Typevar is a generic type-variable that can be bound to any type passed as parameter. The operator ‘ > ’ is overloaded and can be used to com-pare integers as well as floating point numbers. For a call maximum < int > (a, b) , the Object-Oriented Programming Paradigm ◾ 415 type-variable TypeVar will be bound to “int”, and the function will behave as an inte-ger type. For a call maximum < float > (a, b) the function will behave as a “float” type. template < class Typevar> Typevar maximum (Typevar first, Typevar second) { Typevar MaxVal; if (first > second) MaxVal = first; else MaxVal = second; return (MaxVal); } Example 11.6 The following example shows the use of generic method in C#. The procedure swap has a generic type T that can be instantiated at run time to different type parameters, such as int, float . For example, a call swap < int > (ref a, ref b) will bind T to int , and a call swap < float > (ref a, ref b) will bind T to float. - eBook - PDF
- David A. Watt(Author)
- 2006(Publication Date)
- Wiley(Publisher)
When a polymorphic procedure operates on values of unknown type, it cannot know the operations with which that type is equipped, so it is restricted to copying these values. That can be implemented safely and uniformly by copying the pointers to these values. This implementation of parametric polymorphism is simple and uniform, but it is also costly. All values (even primitive values) must be stored in the heap; space must be allocated for them when they are first needed, and deallocated by a garbage collector when they are no longer needed. Summary In this chapter: • We have studied inclusion polymorphism, which enables a subtype or subclass to inherit operations from its parent type or class. • We have studied parametric polymorphism, which enables a procedure to operate uniformly on arguments of a whole family of types, and the related concept of parameterized types. • We have studied type inference, whereby the types of declared entities are not stated explicitly in the program but are left to be inferred by the compiler. • We have studied overloading, whereby several procedures may have the same identifier in the same scope, provided that these procedures have non-equivalent parameter types and/or result types. • We have studied type conversions, both explicit (casts) and implicit (coercions). • We have seen how parametric polymorphism influences the representation of values of different types. Further reading Much of the material in this chapter is based on an illu- minating survey paper by CARDELLI and WEGNER (1985). The authors propose a uniform framework for understand- ing parametric polymorphism, abstract types, subtypes, and inheritance. Then they use this framework to explore the consequences of combining some or all of these concepts in a single programming language. (However, no major language has yet attempted to combine them all.) For another survey of type systems see REYNOLDS (1985).
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.











