COMP201 Java Programming Topic 4: Inheritance Readings: Chapter 5.

Slides:



Advertisements
Similar presentations
Introduction to Java 2 Programming
Advertisements

Object Oriented Programming with Java
1 l Inheritance Basics l Programming with Inheritance l Dynamic Binding and Polymorphism Inheritance.
CS 106 Introduction to Computer Science I 04 / 11 / 2008 Instructor: Michael Eckmann.
Chapter 8 Inheritance Part 2. © 2004 Pearson Addison-Wesley. All rights reserved8-2 Outline Creating Subclasses Overriding Methods Class Hierarchies Inheritance.
Inheritance Inheritance Reserved word protected Reserved word super
ITEC200 – Week03 Inheritance and Class Hierarchies.
CS 106 Introduction to Computer Science I 11 / 26 / 2007 Instructor: Michael Eckmann.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Inheritance and Polymorphism.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 1 Abstract Classes and Interfaces.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Fall 2007CS 2251 Inheritance and Class Hierarchies Chapter 3.
Inheritance. In this chapter, we will cover: The concept of inheritance Extending classes Overriding superclass methods Working with superclasses that.
CS 106 Introduction to Computer Science I 04 / 16 / 2010 Instructor: Michael Eckmann.
Java boot camp1 Subclasses Concepts: The subclass and inheritance: subclass B of class A inherits fields and methods from A. A is a superclass of B. Keyword.
1 Chapter 7 l Inheritance Basics l Programming with Inheritance l Dynamic Binding and Polymorphism Inheritance.
1 Chapter 6 Inheritance, Interfaces, and Abstract Classes.
CS 106 Introduction to Computer Science I 11 / 15 / 2006 Instructor: Michael Eckmann.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
1 Inheritance and Polymorphism. 2 Motivations Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
Inheritance and interfaces A class C1 is derived from class C2, then C1 is called subclass, and C2 is called superclass Superclass-parent, base class Subclass.
COMP201 Java Programming Topic 4: Inheritance Readings: Chapter 5.
Vocabulary Key Terms polymorphism - Selecting a method among many methods that have the same name. subclass - A class that inherits variables and methods.
CS 61B Data Structures and Programming Methodology July David Sun.
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
Comp 249 Programming Methodology Chapter 8 - Polymorphism Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal,
Inheritance and Class Hierarchies Ellen Walker CPSC 201 Data Structures Hiram College.
Features of Object Oriented Programming Lec.4. ABSTRACTION AND ENCAPSULATION Computer programs can be very complex, perhaps the most complicated artifact.
What is inheritance? It is the ability to create a new class from an existing class.
 2002 Prentice Hall. All rights reserved. 1 Introduction to Inheritance Inheritance: –1 of 3 main features of OOP –Form of software reusability –(Derived)
Java™ How to Program, 9/e Presented by: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
Inheritance and Access Control CS 162 (Summer 2009)
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Chapter 5 Objects and Classes Inheritance. Solution Assignments 3 & 4 Review in class…..
MIT AITI 2004 – Lecture 13 Abstract Classes and Interfaces.
1 The finalize, clone, and getClass Methods  The finalize method is invoked by the garbage collector on an object when the object becomes garbage.  The.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
Object Oriented Programming
Chapter 10: Introduction to Inheritance. Objectives Learn about the concept of inheritance Extend classes Override superclass methods Call constructors.
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
Lecture 4: Extending Classes. Concept Inheritance: you can create new classes that are built on existing classes. Through the way of inheritance, you.
CMSC 202 Inheritance II. Version 10/092 Inherited Constructors? An Employee constructor cannot be used to create HourlyEmployee objects. Why not? We must.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 – 9.4.
Interfaces F What is an Interface? F Creating an Interface F Implementing an Interface F What is Marker Interface?
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Inheritance and Class Hierarchies Chapter 3. Chapter Objectives  To understand inheritance and how it facilitates code reuse  To understand how Java.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.
Inheritance ndex.html ndex.htmland “Java.
Inheritance and Polymorphism
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 10 Inheritance and Polymorphism.
COP INTERMEDIATE JAVA Inheritance, Polymorphism, Interfaces.
BY:- TOPS Technologies
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
Inheritance Chapter 7 Inheritance Basics Programming with Inheritance
Inheritance and Polymorphism
Inheritance Chapter 7 Inheritance Basics Programming with Inheritance
Chapter 9 Inheritance and Polymorphism
Extending Classes.
Java Programming Language
Inheritance 2nd Lecture
Inheritance Chapter 7 Inheritance Basics Programming with Inheritance
Inheritance.
CMSC 202 Inheritance II.
Presentation transcript:

COMP201 Java Programming Topic 4: Inheritance Readings: Chapter 5

COMP201 Topic 4 / Slide 2 Objectives and Outline l Objectives: n Understand java inheritance and learn to use it. l Outline n Introduction: concept of inheritance n Deriving a subclass n Using subclasses n Special class types and classes arising from inheritance –Abstract classes –Final classes –The Object class –(The Class class allows you to analyze and manipulate java program at run time.)

COMP201 Topic 4 / Slide 3 Introduction to Inheritance l Technique for deriving a new class from an existing class. l Existing class called superclass, base class, or parent class. l New class is called subclass, derived class, or child class.

COMP201 Topic 4 / Slide 4 l Subclass and superclass are closely related n Subclass share fields and methods of superclass n Subclass can have more fields and methods n Implementations of a method in superclass and subclass can be different n An object of subclass is automatically an object of superclass, but not vice versa –The set of subclass objects is a subset of the set of superclass objects. (E.g. The set of Manager s is a subset of the set of Employee s.) This explains the term subclass and superclass. Introduction to Inheritance

COMP201 Topic 4 / Slide 5 Introduction to Inheritance Why inheritance? Employee class: name, salary, hireDay; getName, raiseSalary(), getHireDay(). Manager is-a Employee, has all above, and l Has a bonus l getsalary() computed differently Instead of defining Manager class from scratch, one can derive it from the Employee class. Work saved.

COMP201 Topic 4 / Slide 6 Introduction to Inheritance Checking method A method B1 Saving method A method B2 Account method A checking method B1 saving method B2 Why inheritance? Inheritance allows one to factor out common functionality by moving it to a superclass, results in better program.

COMP201 Topic 4 / Slide 7 Introduction to Inheritance l Multiple inheritance n A class extends >1 superclasses l Java does not support multiple inheritance n A java class can only extend ONE superclass n Functionality of multiple inheritance recovered by interfaces.

COMP201 Topic 4 / Slide 8 Outline l Outline n Introduction: concept of inheritance n Deriving a subclass n Using subclasses n Special class types and classes arising from inheritance –Abstract classes –Final classes –The Object class

COMP201 Topic 4 / Slide 9 Deriving a Subclass l General scheme for deriving a subclass: class subClassName extends superClassName { constructors refined methods additional methods additional fields } Indicate the differences between subclass and superclass

COMP201 Topic 4 / Slide 10 Deriving a class class Employee { public Employee(String n, double s, int year, int month, int day) {…} public String getName(){…} public double getSalary() {…} public Data getHireDay(){…} public void raiseSalary(double byPercent) {…} private String name; private double Salary; private Date hireDay; }

COMP201 Topic 4 / Slide 11 Deriving a class Extending Employee class to get Manager class class Manager extends Employee { public Manager(…) {…} // constructor public void getSalary(…) {…} // refined method // additional methods public void setBonus(double b){…} // additional field private double bonus; }

COMP201 Topic 4 / Slide 12 Deriving a Class l Plan n Fields of subclass n Constructors of subclass n Methods of subclass n A few notes

COMP201 Topic 4 / Slide 13 Fields of subclass l Semantically: Fields of superclass + additional fields n Employee –Name, salary, hireday n Manager –name, salary, hireday –bonus l Methods in subclass cannot access private fields of superclass. n After all, subclass is another class viewed from super class. n More on this later.

COMP201 Topic 4 / Slide 14 Fields of subclass l Static instance fields are inherited but not duplicated in subclass. class Employee // StaticInherit.java { public Employee ( … ) { … numCreated++; } public static int getNumCreated() { return numCreated; } … private static int numCreated=0; } Manager b = new Manager( … ); // numCreated = 1 Employee e = new Employee( … ); // numCreated = 2 Employee.getNumCreated(); // 2 Manager.getNumCreated(); // 2

COMP201 Topic 4 / Slide 15 Fields of subclass To count number of Managers separately, declare a new static variable in Manager class class Manager extends Employee { public Manager ( … ) { … numManager++; } public static int getNumCreated() { return numManager; } … private static int numManager=0; } // StaticInherit1.java

COMP201 Topic 4 / Slide 16 Deriving a Class l Plan n Fields of subclass n Constructors of subclass n Methods of subclass n A few notes

COMP201 Topic 4 / Slide 17 Constructors of Subclass l Every constructor of a subclass must, directly or indirectly, invoke a constructor of its superclass to initialize fields of the superclass. (Subclass cannot access them directly) Use keyword super to invoke constructor of the superclass. public Manager(String n, double s, int year, int month, int day) { super(n, s, year, month, day); bonus = 0; } Must be the first line

COMP201 Topic 4 / Slide 18 l Can call another constructor of subclass. n Make sure that constructor of superclass is eventually called. public Manager(String n) { this(n, 0.0, 0, 0, 0); } Constructors of Subclass

COMP201 Topic 4 / Slide 19 l If subclass constructor does not call a superclass constructor explicitly, then superclass uses its default constructor. class FirstFrame extends JFrame { public FirstFrame() { setTitle("FirstFrame"); setSize(300, 200); } } If superclass has no default constructor, compiler error Constructor of Subclass super() implicitly called here

COMP201 Topic 4 / Slide 20 l Constructors are not inherited. Let’s say Employee has two constructors public Employee(String n, double s, int year, int month, int day) public Employee(String n, double s) Manager has one constructor public Manager(String n, double s, int year, int month, int day) new Manager( “ George ”, 20000, 2001, 7, 20 ); //ok new Manager( “ Jin ”, 25); //not ok Constructors of Subclass

COMP201 Topic 4 / Slide 21 Deriving a Class l Plan n Fields of subclass n Constructors of subclass n Methods of subclass n A few notes

COMP201 Topic 4 / Slide 22 Methods of Subclass l Methods of subclass include n Non-private methods of superclass that are not refined (inherited). n + Refined (overriding) methods n + Additional methods l Refined and additional methods appear in subclass

COMP201 Topic 4 / Slide 23 Overriding Methods Salary computation for managers are different from employees. So, we need to modify the getSalary, or provide a new method that overrides getSalary public double getSalary( ) { double baseSalary = super.getSalary(); return basesalary + bonus; } l Cannot replace the last line with salary += bonus; Because salary is private to Employee. l Cannot drop “super.”, or else we get an infinite loop Call method of superclass

COMP201 Topic 4 / Slide 24 Overriding Methods l An overriding method must have the same signature (name and parameter list) as the original method. Otherwise, it is simply a new method: Original Method in Employee : public double getSalary( ){…} public void raiseSalary(double byPercent){…} New rather than overriding methods in Manager: public void raiseSalary(int byPercent){…} public void raiseWage(double byPercent){…}

COMP201 Topic 4 / Slide 25 Overriding Methods n An overriding method must have the same return type as the original method: –The following method definition in Manager would lead to compiler error: public int getSalary( ){…} An overriding method must be at least as visible as the superclass method. private methods cannot be overridden, but others (public, protected, default-access methods) can.

COMP201 Topic 4 / Slide 26 Additional Methods public void setBonus(double b) { bonus = b; }

COMP201 Topic 4 / Slide 27 Methods for Subclass Manager Inherited from Employee getName, getHirDay, raiseSalary Refined from Employee getSalary. l Additional Manager, setBonus.

COMP201 Topic 4 / Slide 28 Deriving a Class l Plan n Fields of subclass n Constructors of subclass n Methods of subclass n A few notes

COMP201 Topic 4 / Slide 29 Note about this n Refer to another constructor in the same class class Employee { public Employee(String n, double s, int year, int month, int day){…} public Employee(String n) // another constructor { this(n, 0, 0,0,0); // salary default at 0 }

COMP201 Topic 4 / Slide 30 Note about this n Refers to the current object public Employee(String n, double s, int year, int month, int day) { this.name = n; this.salary = s; GregorianCalendar calendar = new GregorianCalendar(year, month - 1, day); // GregorianCalendar uses 0 for January this.hireDay = calendar.getTime(); }

COMP201 Topic 4 / Slide 31 Note about super A special keyword that directs the compiler to invoke the superclass constructor and method l Refers to constructor of superclass public manager(String n, double s, int year, int month, int day) { super(n, s, year, month, day);} l Invokes a superclass method public double getSalary() { double baseSalary = super.getSalary(); return baseSalary + bonus; } It does not refer to an object. There isn’t another object to refer to!

COMP201 Topic 4 / Slide 32 Note about Protected Access A subclass can access protected fields and methods of a superclass Example: If the hireDay field of Employee is made protected, then methods of Manager can access it directly. However, methods of Manager can only access the hireDay field of Manager objects, not of other Employee objects. (See next slide for more explanation) Protected fields are rarely used. Protected methods are more common, e.g. clone of the Object class (to be discussed later)

COMP201 Topic 4 / Slide 33 public class Employee { … protected Date hireDay; } Public class Manager extends Employee { someMethod() { Employee boss = new Manager(); boss.hireDay //ok Employee clerk = new Employee(); clerk.hireDay // not ok } Note about Protected Access

COMP201 Topic 4 / Slide 34 When to use the protected modifier: n Best reserved specifically for subclass use. n Do not declare anything as protected unless you know that a subclass absolutely needs it. –clone of the Object class n In general, do not declare methods and attributes as protected in the chance that a subclass may need it sometime in the future. n If your design does not justify it explicitly, declare everything that is not in the public interface as private. Note about Protected Access

COMP201 Topic 4 / Slide 35 Note about Inheritance Hierarchies l Can have multiple layers of inheritance: class Executive extends Manager { ….} l Inheritance hierarchy: inheritance relationships among a collection of classes EmployeeSecretaryManagerProgrammerExecutive

COMP201 Topic 4 / Slide 36 Outline l Outline n Introduction: concept of inheritance n Deriving a subclass n Using subclasses n Special class types and classes arising from inheritance –Abstract classes –Final classes –The Object class

COMP201 Topic 4 / Slide 37 Using Subclasses l Plan: n Class compatibility: –An object of subclass is automatically an object of superclass, but not vice versa. l Employee harry = new Employee(); l Employee jack = new Manager(); n Polymorphism: –Object variable an refer to multiple actual types n Dynamic binding –Java’s ability to call the appropriate method depending on actual type of object l harry.getSalary(); l jack.getSalary();

COMP201 Topic 4 / Slide 38 Class Compatibility l Object of a subclass can be used in place of an object of a superclass Manager harry = new Manager( … ); Employee staff = harry; Employee staff1 = new Manager( … ); harry automatically cast into an Employee, widening casting. Why does staff.getSalary() work correctly? Employee has method getSalary. No compiling error. l Correct method found at run time via dynamic binding

COMP201 Topic 4 / Slide 39 Class Compatibility l The opposite is not true Employee harry = new Employee( … ); Manager staff = harry;// compiler error Manager staff1 = new Employee( … ); // compiler error

COMP201 Topic 4 / Slide 40 Narrowing cast l Only necessary when n Object of subclass was cast into object of a superclass, and want to get back the original class type Manager carl = new Manager( … ); Employee staff = carl; // This will produce a compiler error, since Employee // doesn’t has setbonus method staff.setbonus(5000); //cast is required to get back the original class type Manager b = (Manager) staff; b.setbonus(5000);

COMP201 Topic 4 / Slide 41 l One bad narrowing cast terminates program Make sure narrowing cast is legal using operator instranceof Manager carl = new Manager( … ); Employee staff1 = carl; Employee staff2 = new Employee(…); Manager b1 = (Manager) staff1; // ok Manager b2 = (Manager) staff2; // crashes if ( staff2 instanceof Manager ) Manager b2 = (Manager) staff2; // does not crash Narrowing cast

COMP201 Topic 4 / Slide 42 Using Subclasses l Plan: n Class compatibility: n Polymorphism: n Dynamic binding

COMP201 Topic 4 / Slide 43 Polymorphism & Dynamic binding l Method call: case 1 Employee harry = new Employee( … ); harry.getSalary(); // calls method of Employee l Method call: case 2 Manager carl = new Manager( … ); carl.getSalary(); // calls method of Manager l Method call: case 3 Manager carl = new Manager( … ); Employee staff = carl; staff.getSalary();  Calls method of Employee or Manager?  Answer: method of Manager.

COMP201 Topic 4 / Slide 44 l How does java call the correct method? Consider method call x.f(args), where x declared as “ C x ” –Compiler Enumerate all methods called f in C and non-private methods named f in superclasses of C. l Does overloading resolution. If f is a private, static, final method, compiler knows exactly which method to call. (Static binding). –JVM Start with the actual type of x. If f not found there, move to superclass. And so on. (Dynamic binding) l Method table utilized to make this more efficient. Polymorphism & Dynamic binding

COMP201 Topic 4 / Slide 45 Manager carl = new Manager(…); Employee staff = carl; Staff.getSalary(); //Try Manager. Found. staff.getHireDay(); //Try Manager. Not found. Move to Employee. Found. l Implication: method in subclass hides (overrides) method in superclass Polymorphism & Dynamic binding ManagerTest.java

COMP201 Topic 4 / Slide 46 Outline l Outline n Introduction: concept of inheritance n Deriving a subclass n Using subclasses n Special class types and classes arising from inheritance –Abstract classes –Final classes –The Object class

COMP201 Topic 4 / Slide 47 Consider two classes: Employee and Student l Common methods: n getName getDescription : returns –Employee : “an employee with salary $50,000” –Student : “a student majoring in Computer Science” To write better code, introduce a superclass Person with those two methods Abstract Classes PersonStudentEmployee

COMP201 Topic 4 / Slide 48 class Person { public Person(String n) { name = n;} public String getName() { return name;} public String getDescription(); // but how to write this? private String name; } The Person class knows nothing about the person except for the name. We don’t know how to implement the method in the Person class although we know it must be there. Abstract Classes

COMP201 Topic 4 / Slide 49 Solution: leave the getDescription method abstract Hence leave the Person class abstract abstract class Person { public Person(String n) { name = n;} public abstract String getDescription(); public String getName() { return name;} private String name; } Abstract Classes

COMP201 Topic 4 / Slide 50 l An abstract method is a method that n Cannot be specified in the current class (C++: pure virtual function). n Must be implemented in non-abstract subclasses. l An abstract class is a class that may contain one or more abstract methods l Notes: n An abstract class does not necessarily have abstract method n Subclass of a non-abstract class can be abstract. Abstract Classes

COMP201 Topic 4 / Slide 51 l Cannot create objects of an abstract class: New Person(“Micky Mouse”) // illegal l An abstract class must be extended before use. class Student extends Person { public Student(String n, String m) { super(n); major = m;} public String getDescription() { return "a student majoring in " + major; } private String major; } Abstract Classes

COMP201 Topic 4 / Slide 52 class Employee extends Person { … public String getDescription() { NumberFormat formatter = NumberFormat.getCurrencyInstance(); return "an employee with a salary of " + formatter.format(salary); } … private double salary; } Abstract Classes

COMP201 Topic 4 / Slide 53 Person[] people = new Person[2]; people[0]= new Employee("Harry Hacker", 50000, 1989,10,1); people[1]= new Student("Maria Morris", "computer science"); for (int i = 0; i < people.length; i++) { Person p = people[i]; System.out.println(p.getName() + ", " + p.getDescription()); } //PersonTest.java This would not compile if we don’t have getDescription in Person. Abstract Classes

COMP201 Topic 4 / Slide 54 Outline l Outline n Introduction: concept of inheritance n Deriving a subclass n Using subclasses n Special class types and classes arising from inheritance –Abstract classes –Final classes –The Object class

COMP201 Topic 4 / Slide 55 l Final method: Declared with keyword final n Cannot be overridden in subclasses class Employee { … public final String getName() {…} } Final Methods and Classes

COMP201 Topic 4 / Slide 56 l Final class Declared with keyword final n Cannot be sub-classed. Opposite of abstract class. All methods are final. final class Executive extends Manager { …. } Final Methods and Classes

COMP201 Topic 4 / Slide 57 Reasons to use final methods (and final classes): n Efficiency: –Compiler put final method in line: e.getName() replaced by e.name. –No function call. –No dynamic binding. n Safety: –Other programmers who extend your class cannot redefine a final method. Final Methods and Classes

COMP201 Topic 4 / Slide 58 l Wrapper classes for primitive types are final n Primitive types –boolean, char, byte, short, int, long, float, double, void n Wrapper classes –Boolean, Character, Byte, Short, Integer, Long, Float, Double, Void n Methods of java.lang.Integer –int intValue(), –Static String toString(int i) // cannot override to print in another way –static int parseInt( String s) –static Integer valueOf(String s) –... Final Methods and Classes

COMP201 Topic 4 / Slide 59 Outline l Outline n Introduction: concept of inheritance n Deriving a subclass n Using subclasses n Special class types and classes arising from inheritance –Abstract classes –Final classes –The Object class

COMP201 Topic 4 / Slide 60 The Object class The Object class ( java.lang.Object ) is the mother of all classes Everything eventually is related to Object Never write class Employee extends Object {…} because Object is taken for granted if no explicitly superclass: class Employee {…} Object NumberArrayString IntegerDouble IS-A..

COMP201 Topic 4 / Slide 61 l Has a small set of methods n boolean equals(Object other); –x.equals(y); for any reference values x and y, this method returns true if and only if x and y refer to the same object (x==y has the value true). –Must be overridden for other equality test, e.g. name, or id E.g. Overridden in String String toString(); –Returns a string representation of the object –System.out.println(x) calls x.toString() –So does “”+x –Override it if you want better format. –Useful for debugging support n Other methods to be discussed later. The Object class

COMP201 Topic 4 / Slide 62 The Object class gives us one way to do generic programming (There are other ways, e.g. interfaces.) int find(Object[]a, Object key) { int i; for (i=0; i<a.length; i++) { if (a[i].equals(key)) return i; } return –1; // not found } The function can be applied to objects of any class provided that the equals method is properly defined for that class Employee[] staff = new Employee[10]; Employee harry; … int n = find(staff, harry); The Object class Assuming Employee has method public boolean equals(Employee){…};

COMP201 Topic 4 / Slide 63 Suppose Employee has public equals(int ID){…}; Can we call find(staff, 5)? n No, because 5 is not an object of any class. l What should we if we want to use ID-based equality test? n Use rapper class –Instead of equals(int ID), define equals(Integer ID) –Then, call find(staff, new Integer(5)); The Object class

COMP201 Topic 4 / Slide 64 Example of generic programming: java.util.ArrayList Array-like class that manages objects of type Object, and that n Grows and shrinks dynamically (no need to specify size) n Very useful. l Methods: // ArrayListTest.java ArrayList(),ArrayList(int initialCapacity) //constructors int size() boolean add(Object obj) // append element boolean add(int index, Object obj) void remove(int index) void set(int index, Object obj) Object get(int index) // needs to cast to appropriate type The Object class

COMP201 Topic 4 / Slide 65 Summary of Modifiers n Class Modifiers  public: Visible from other packages  default (no modifier): Visible in package  final: No subclasses  abstract: No instances, only subclasses n Field modifiers  public: visible anywhere  protected: visible in package and subclasses  default (no modifier): visible in package  private: visible only inside class  final: Constant  static: Class variable

COMP201 Topic 4 / Slide 66  Method Modifiers  final: No overriding  static: Class method  abstract: Implemented in subclass  native: Implemented in C  private, public, protected, default: Like variables Summary of Modifiers