1 final (the keyword, not the exam). 2 Motivation Suppose we’ve defined an Employee class, and we don’t want someone to come along and muck it up  E.g.,

Slides:



Advertisements
Similar presentations
Object Oriented Programming
Advertisements

METHOD OVERRIDING 1.Sub class can override the methods defined by the super class. 2.Overridden Methods in the sub classes should have same name, same.
Interfaces and polymorphism Chapter 9. Interfaces  Used to express operations common to more than one purpose.  Example: You want to find the maximum.
Chapter 8 – Interfaces and Polymorphism Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
ACM/JETT Workshop - August 4-5, :Inheritance and Interfaces.
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Chapter Three - Implementing Classes.
Inheritance The objectives of this chapter are: To explore the concept and implications of inheritance Polymorphism To define the syntax of inheritance.
Interfaces. Lecture Objectives To learn about interfaces To be able to convert between class and interface references To appreciate how interfaces can.
Copyright 2008 by Pearson Education Building Java Programs Chapter 9 Lecture 9-2: Static Data; More Inheritance reading:
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 9: Inheritance and Interfaces.
Interfaces. Lecture Objectives To learn about interfaces To be able to convert between class and interface references To appreciate how interfaces can.
1 Inheritance Readings: Writing classes Write an Employee class with methods that return values for the following properties of employees at a.
Copyright 2008 by Pearson Education Building Java Programs Chapter 9 Lecture 9-1: Inheritance reading:
Copyright 2010 by Pearson Education Topic 31 - inheritance.
MIT AITI 2002 Abstract Classes, Interfaces. Abstract Classes What is an abstract class? An abstract class is a class in which one or more methods is declared,
1 Abstract Class There are some situations in which it is useful to define base classes that are never instantiated. Such classes are called abstract classes.
Inheritance - CIS 1068 Program Design and Abstraction Zhen Jiang CIS Dept. Temple University 1050 Wachman Hall, Main Campus
CS305j Introduction to Computing Inheritance and Polymorphism 1 Topic 26 Introduction to Inheritance and Polymorphism "One purpose of CRC cards [a design.
COP 2800 Lake Sumter State College Mark Wilson, Instructor.
 2002 Prentice Hall. All rights reserved. 1 Introduction to Inheritance Inheritance: –1 of 3 main features of OOP –Form of software reusability –(Derived)
CSC 142 Computer Science II Zhen Jiang West Chester University
Copyright 2008 by Pearson Education Building Java Programs Chapter 8 Lecture 19: encapsulation, inheritance reading: (Slides adapted from Stuart.
Chapter 9 Interfaces and Polymorphism. Chapter Goals To learn about interfaces To be able to convert between class and interface references To understand.
Copyright 2008 by Pearson Education Building Java Programs Chapter 9 Lecture 9-1: Inheritance reading:
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 10 - Interfaces.
Some Object-Oriented Programming (OOP) Review. Let’s practice writing some classes Write an Employee class with methods that return values for the following.
1 Building Java Programs Chapter 9: Inheritance and Interfaces These lecture notes are copyright (C) Marty Stepp and Stuart Reges, They may not be.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
MIT AITI 2004 – Lecture 13 Abstract Classes and Interfaces.
Copyright 2008 by Pearson Education Building Java Programs Chapter 9 Lecture 9-2: Static Data; More Inheritance reading:
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.
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
Drew University1 Interfaces and Polymorphism 9.1 Developing Reusable Solutions 9.2 Converting between Types 9.3 Polymorphism Common Error 9.1 Advanced.
Copyright 2010 by Pearson Education Building Java Programs Chapter 9 Lecture 9-1: Inheritance reading: 9.1.
Copyright 2008 by Pearson Education Building Java Programs Chapter 9 Lecture 9-2: Interacting with the Superclass ( super ) reading:
Inheritance and Subclasses CS 21a. 6/28/2004 Copyright 2004, by the authors of these slides, and Ateneo de Manila University. All rights reserved L16:
Copyright 2008 by Pearson Education Building Java Programs Chapter 9 Lecture 9-2: Interacting with the Superclass ( super ); Discussion of Homework 9:
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 Interfaces and Abstract Classes The ability to define the behavior of an object without specifying that behavior is to be implemented Interface class.
OOP in Java : © W. Milner 2005 : Slide 1 Java and OOP Part 3 – Extending classes.
POLYMORPHISM Chapter 6. Chapter Polymorphism  Polymorphism concept  Abstract classes and methods  Method overriding  Concrete sub classes and.
OOP Basics Classes & Methods (c) IDMS/SQL News
Copyright 2008 by Pearson Education Building Java Programs Chapter 9: Inheritance and Interfaces Lecture 9-1.
CSC 205 Programming II Lecture 4 Abstract Class. The abstract keyword indicate that a class is not instantiable Defining a type which will be specialized.
CS 116 Object Oriented Programming II Lecture 9 Acknowledgement: Contains materials provided by George Koutsogiannakis and Matt Bauer.
1 Interacting with the superclass (continued) suggested reading:9.4.
Chapter 15 Abstract Classes and Interfaces
Chapter Goals To be able to declare and use interface types
Building Java Programs Chapter 9
Inheritance - CIS 1068 Program Design and Abstraction
Lecture 15: More Inheritance
Lecture 9-2: Interacting with the Superclass (super);
Chapter Three - Implementing Classes
Interface.
Week 6 Object-Oriented Programming (2): Polymorphism
Building Java Programs
Java Inheritance.
Lecture 14: Inheritance Building Java Programs: A Back to Basics Approach by Stuart Reges and Marty Stepp Copyright (c) Pearson All rights reserved.
Building Java Programs
Topic 31 - inheritance.
Building Java Programs
Inheritance Readings: 9.1.
Lecture 15: Inheritance II
Chapter 14 Abstract Classes and Interfaces
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Presentation transcript:

1 final (the keyword, not the exam)

2 Motivation Suppose we’ve defined an Employee class, and we don’t want someone to come along and muck it up  E.g., we don’t want a CEO subclass that gives itself a raise The final keyword indicates that some definition (of a class, method, or field) cannot be changed or overridden by a subclass.

3 final Example // A class to represent employees public class Employee { public int getHours() { return 40; // works 40 hours / week } public final double getSalary() { return ; // $40, / year } public int getVacationDays() { return 10; // 2 weeks' paid vacation } public String getVacationForm() { return "yellow"; // use the yellow form } No subclass is allowed to change the definition of getSalary()!

4 final fields, methods, and classes The final keyword can be applied to fields (as we’ve seen before): // no code may change the value of salary, //including a subclass’s code public final double salary = ; Or to methods: // subclasses cannot override the getSalary method public final double getSalary() { return salary; } Or even to classes: // the Employee class cannot be extended // It can’t have any subclasses at all! public final class Employee {... }

Exercise: Update the Employee class Add final declarations to the Employee class below so that different subclasses can have different salaries, but once their salary is set, they can’t be changed. public class Employee { private double salary; public Employee(int sal) { salary = sal; } public double getSalary() { return salary; }

6 abstract

Opposite of final The final keyword prevents subclasses from changing (overriding) code Sometimes, you want to do the opposite: Force another programmer or piece of code to finish parts of a class.

Example: Employee salary Let’s say you want every subclass of Employee to have a salary, but you want the subclass to decide what the salary should be. We can define an “abstract” getSalary() method: public abstract double getSalary(); Note: no method definition!  Abstract method declarations don’t provide definitions, just signatures.  They are there to force subclasses to provide the definitions.

Abstract Rules (1) 1. If a class has an abstract method, or it inherits an abstract method that it doesn’t override, then the class must be declared abstract. public abstract class Employee { public abstract double getSalary(); // you can mix abstract and non-abstract methods // in an abstract class public int getHours() { // Note: not abstract! return 40; }

Abstract Rules (2) 2. If a class is abstract, it can’t have a constructor.  No Employee object can be constructed  But you can declare Employee references. public abstract class Employee { public abstract double getSalary(); public static void main(String [] args) { Employee e;// NO ERROR: reference is fine e = new Employee(); // ERROR! No constructor }

Extending an abstract class public class Lawyer extends Employee { // since Employee declares an abstract getSalary, // Lawyer must define getSalary by overriding it // or else Lawyer must be an abstract class public double getSalary() { return ; } public static void main(String [] args) { Employee e;// Fine, no problem e = new Lawyer(); // Also fine (polymorphism) e = new Employee(); // ERROR! No constructor! }

Abstract classes: what’s the point? If you can’t construct objects for a class, what’s the point of the class? How can we use it?  Short Answer: polymorphism.  We can use references of type Employee as a place to store Lawyers, Secretaries, CEOs, etc.  Because getSalary() is declared in Employee, e.getSalary() is legal syntax, even though getSalary() is not defined in Employee.

Exercise Create an abstract ClosedShape class with an abstract getArea() method Include a non-abstract (aka, concrete) method in ClosedShape that prints the area of the shape to the screen. Write non-abstract (aka, concrete) subclasses Rectangle and Circle Write main methods for each that construct an object and print its area.

14 Interfaces Completely abstract.

15 Going full abstract What if our abstract class had no non-abstract methods? public abstract class Employee { public abstract double getSalary(); public abstract int getHours(); public abstract String getVacationForm(); } Each subclass would have different definitions. They share only the names of their methods. Java has an alternative way to do this: interfaces

16 Interfaces Let's say you have the following two related classes: public class Scientist { public void discover() { System.out.println(“Eureka! I have found it!“); } public void publish() { System.out.println(“My research is better than yours.”); } public class Engineer { public void discover() { System.out.println(“Cool, what did I just do?“); } public void publish() { System.out.println(“I don't know how this happened, but it works.”); } Neither of their methods do the same thing.

17 Code Reuse But they're still similar – they both discover and publish. Can we get code reuse? interface Researcher { void discover(); void publish(); } But why? What does that accomplish?  Now we can create Researcher references

18 Using Interface Objects public static void researchCycle(Researcher r) { r.discover(); r.publish(); } public static void main(String [] args) { Researcher researcher1 = new Scientist(); Researcher researcher2 = new Engineer(); // Interfaces have no constructors // They can only be used as types for references researcher2 = new Researcher(); // ERROR! researchCycle(researcher1); researchCycle(researcher2); }

19 Using Interfaces Interfaces are a way of specifying what objects are capable of, without saying how. Interface variables can execute any of the methods listed in the interface, but the behavior depends on the class of the object  That is, interface variables are polymorphic. There are no constructors for interfaces. They are not classes, and no objects of that run- time type are created. They are compile-time types for references.

20 Implementing Interfaces public class Scientist implements Researcher { public void discover() { System.out.println(“Eureka! I have found it!“); } public void publish() { System.out.println(“My research is better than yours.”); }

21 Implementing Interfaces public class Engineer implements Researcher { public void discover() { System.out.println(“Whoa, what did I just do?“); } public void publish() { System.out.println(“I don't know how this happened, but it works.”); }

Exercise: Comparable interface Define the Comparable interface public interface Comparable { public int compareTo(Object other); } public interface Comparable { public int compareTo(T other); }

Exercise: Dataset with Interfaces Below is a dataset class that finds the maximum and average of a set of ints. Modify the dataset class so that it works for any class which implements the right interface (that you define). Create a BankAccount class that implements your interface, and use Dataset to find the BankAccount with the maximum balance.

Dataset class (to be modified) public class Dataset { private int count = 0; private int maximum = Integer.MIN_INT; private double sum = 0; public void add(int x) { sum += x; count++; if(x > maximum) { maximum = x; } } public int getMaximum() { return maximum; } public double getAvg() { return sum / count; } }

BankAccount (to be modified) public class BankAccount { private double balance = 0; public BankAccount(double initBalance) { balance = initBalance; } public double getBalance() { return balance; } public static BankAccount getMaxAcct( BankAccount [] accounts) { // fill this in! }

BankAccount (solution) public class BankAccount implements Measurable { private int balance = 0; public BankAccount(int initBalance) { balance = initBalance; } public int getBalance() { return balance; } public int getMeasure() { return getBalance(); } public BankAccount getMaxAcct(BankAccount [] accounts) { Dataset d = new Dataset(); for(int i=0; i<accounts.length; i++) { d.add(accounts[i]); } return (BankAccount)d.getMaximum(); }