
Understanding Java Method Overriding and Polymorphism
Explore the concepts of method overriding and polymorphism in Java, where subclasses can replace superclass method implementations and a method can take different forms depending on the underlying class. Learn how subclass variables override superclass variables and how the 'super' keyword allows access to hidden superclass variables and methods. Understand the importance of initializing superclass state in subclass instances using constructors and the 'super()' method.
Uploaded on | 0 Views
Download Presentation

Please find below an Image/Link to download the presentation.
The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author. If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.
You are allowed to download the files provided on this website for personal or commercial use, subject to the condition that they are used lawfully. All files are the property of their respective owners.
The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author.
E N D
Presentation Transcript
CMPU-102-01 Fall 2021 Data Structures and Algorithms Week 8: More about Java methods continued; More about classes Rui Meireles Peter Lemieszewski Computer Science Department, Vassar College, USA 1
More about methods Overriding a method 2
Method overriding Subclasses can replace a superclass' method implementation by specifying a method with the same signature Same name, return type, and parameter list We call this method overriding At runtime, the subclass method will be the one executed Even in situations like these: public class SuperClass{ int m(){ return 0; } } public class SubClass extends SuperClass{ int m(){ return 1; } } SuperClass s = new SubClass(); System.out.println(s.m()); 3
Polymorphism Polymorphism (from the Greek for many forms ) A polymorphic method is a method that is overridden by subclass(es) Each class implements its own version of the method E.g. the String toString() method The method takes many forms, depending on the underlying class Person getMealPrice() Student Employee getMealPrice() getMealPrice() 4
Overriding variables Subclass variables override superclass variables of the same name, regardless of type Example: public class Person{ long ssn; } public class Student extends Person{ String ssn; Student(String ssn){ this.ssn = ssn; } } If the superclass variable is hidden, does that mean it s gone ? 5
The super keyword super allows subclasses to access variables and methods of the superclass that are hidden due to overriding Example: public class Person{ protected long ssn = 1; ... String toString(){ return "Person"; } } public class Student extends Person{ String ssn; long studentId; String toString(){ return super.toString() + "Student"; } void someMethod(){ this.ssn = "Twenty nine"; super.ssn = 29; } } 6
The super keyword and constructors Subclass instances inherit superclass state Therefore, when we create an object of a subclass, the state of the superclass must be initialized as well Can use super()to call the superclass s constructor from the subclass s one Java inserts a super()if we don t write one This requires superclass to have empty constructor If we want to call a constructor with arguments, an explicit call is needed Calling super()allows initialization the superclass s private fields Can t access them directly from subclass Example: public class Person{ private String name; Person(String name){ this.name = name; } } } public class Student extends Person{ long studentId; Student(String name, long studentId){ super(name); this.studentId = studentId; } 7
Method overloading A class can define multiple methods of the same name but featuring distinct parameter lists For example, constructors with differing number of arguments: class Person{ String name; Person(){ this.name = "John Doe"; } Person(String name){ this.name = name; } } We say the method is overloaded All variants must have the same return type You ve used an overloaded method before: println() Be sure to distinguish method overloading from method overriding 8
More about classes (IPUJ Sections 5.1-5.7) 9
Abstract classes Some classes act as templates for subclasses and should not be instantiated. E.g. the Function class in lab #1: All of its methods were empty stubs! 10
Abstract classes The abstractkeyword marks a class that can t be instantiated Regular classes are called concrete, by way of contrast Syntax: <access> abstract class <ClassName>{ } E.g. public abstract class AFunction { } Good practice dictates class name should start with a capital A An abstract class can have: Fields Regular concrete methods Abstract (bodyless) methods that must be instantiated by the subclasses E.g. public abstract class AFunction{ public abstract double imageOf(double x); public abstract double root(); public String toString(){ return "Abstract function"; } } 11
Final classes Abstract classes must be extended to be instantiated finalclasses can not be extended (and hence can t be abstract) Syntax: <accessModifier> final class <ClassName>{ } Useful for defining libraries of static constants and methods, e.g.: public final class Math{ public static final double PI = 3.14159265358979323846; public static final double E = 2.718; public static double random(){ } } Can also be used to prevent others from building upon your code 12
Interfaces Define a data type in the form of a name and a set of methods Establishes behavior from user s point of view, also known as Abstract Data Type (ADT) Largely a replacement for multiple inheritance Syntax: Definition:public interface <InterfaceName> {} Usage: class <ClassName> implements <InterfaceName1>, <InterfaceName2>, Do not contain any instance fields or constructors Because interfaces can t be instantiated Define an implements relationship instead of an is-a relationship 13
Interface definition and usage example public interface IReadable{ public abstract String read(); } public interface IWritable{ public abstract void write(String s); } public class Notebook implements IReadable, IWritable{ public String read(){ // read from notebook } public void write(String s){ // write to notebook } } 14
More about interfaces Interfaces are used to separate specification from implementation Traditionally interface implementors do not inherit behavior But do get the benefits of polymorphism Details: All methods are public (keyword may be omitted) All non-static methods are abstract (keyword may be omitted) May containpublic static finalclass fields, i.e. constants (keywordspublic static finalmay be omitted) but no instance fields Names commonly start with a capital I Starting with Java 8, methods can have a method body marked default Provide a default implementation if the implementor has none Useful for adding new functionality to interfaces while maintaining retro- compatibility with old implementors E.g. public default String getName(){ return ""; } 15
The Comparable interface All implementing classes have an order between objects Useful for sorting Defines a single method: compareTo(<type> obj): returns a negative integer, zero, or a positive integer as the this object is less than, equal to, or greater than the argument object Example: public class Person implements Comparable{ long ssn; ... public int compareTo(Person oper){ return (int) (this.ssn - oper.ssn); } } 16
Wrapper classes Java features primitive types for efficiency (both temporal and spatial) But there are many methods in the Java libraries that only work with objects For instance sorting a collection of Comparable objects To get around this problem, Java includes a wrapper class for each of the primitive types: boolean byte char double Boolean Byte Character Double float int long short Float Integer Long Short 17
Using wrapper classes We can create an instance of a wrapper class by calling its constructor with the primitive value. For example, the line: Integer five = new Integer(5); creates a new Integer object containing the value 5. For each of the wrapper classes, Java also defines a method to retrieve the primitive value inside: int underlyingValue = five.intValue(); These operations are called boxing and unboxing 18
Autoboxing and unboxing Starting with Java 5, conversion between a primitive type and the corresponding wrapper class is performed automatically. E.g.: Integer five = 5; Will automatically call the Integer constructor. Similarly, if we write: int six = five + 1; Java will automatically call five.intValue() before the addition. Although autoboxing and unboxing are convenient, they can generate confusion and should be used with care 19