CS 61B Data Structures and Programming Methodology July 2, 2008 David Sun.

Slides:



Advertisements
Similar presentations
Object Oriented Programming with Java
Advertisements

Lecture 5: Interfaces.
SUMMARY: abstract classes and interfaces 1 Make a class abstract so instances of it cannot be created. Make a method abstract so it must be overridden.
Lecture 17 Abstract classes Interfaces The Comparable interface Event listeners All in chapter 10: please read it.
1 Lecture 3 Inheritance. 2 A class that is inherited is called superclass The class that inherits is called subclass A subclass is a specialized version.
CS 106 Introduction to Computer Science I 11 / 20 / 2006 Instructor: Michael Eckmann.
Interfaces. In this class, we will cover: What an interface is Why you would use an interface Creating an interface Using an interface Cloning an object.
1 Chapter 6 Inheritance, Interfaces, and Abstract Classes.
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.
CS 106 Introduction to Computer Science I 04 / 21 / 2008 Instructor: Michael Eckmann.
CS 106 Introduction to Computer Science I 04 / 28 / 2010 Instructor: Michael Eckmann.
Inheritance and Polymorphism CS351 – Programming Paradigms.
CS 61B Data Structures and Programming Methodology July David Sun.
16-Aug-15 Air Force Institute of Technology Electrical and Computer Engineering Object-Oriented Programming in Java Topic : Interfaces, Copying/Cloning,
Chapter 11 Abstract Classes and Interfaces 1. Abstract method New modifier for class and method: abstract An abstract method has no body Compare: abstract.
CMSC 202 Interfaces. 11/20102 Classes and Methods When a class defines its methods as public, it describes how the class user interacts with the method.
CSE 331 Software Design & Implementation Hal Perkins Autumn 2012 Java Classes, Interfaces, and Types 1.
Chapter 6 Class Inheritance F Superclasses and Subclasses F Keywords: super F Overriding methods F The Object Class F Modifiers: protected, final and abstract.
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 Lecture 07 Interfaces and related issues Reading for these lectures: Weiss, Section 4.4 (The interface), p ProgramLive, Section 12.1 In User Interface.
1 Object-Oriented Software Engineering CS Interfaces Interfaces are contracts Contracts between software groups Defines how software interacts with.
CS 106 Introduction to Computer Science I 04 / 20 / 2007 Instructor: Michael Eckmann.
Recitation 4 Abstract classes, Interfaces. A Little More Geometry! Abstract Classes Shape x ____ y ____ Triangle area() base____ height ____ Circle area()
1 1 Abstract Classes and Interfaces. 22 Motivations You learned how to write simple programs to display GUI components. Can you write the code to respond.
CS 106 Introduction to Computer Science I 04 / 23 / 2010 Instructor: Michael Eckmann.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 10 - Interfaces.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
CS 61B Data Structures and Programming Methodology July 3, 2008 David Sun.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
HashCode() 1  if you override equals() you must override hashCode()  otherwise, the hashed containers won't work properly  recall that we did not override.
Abstract Classes and Interfaces Chapter 9 CSCI 1302.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
1 Abstract Classes and Interfaces. 2 The abstract Modifier  The abstract class –Cannot be instantiated –Should be extended and implemented in subclasses.
Chapter 6 Interfaces. Class Status CU will be close for winter break from Dec. 22. till Jan.2 We have 3 classes left after tonight (Jan 8,15, and 22)
MIT AITI 2004 – Lecture 13 Abstract Classes and Interfaces.
Chapter 7: Class Inheritance F Superclasses and Subclasses F Keywords: super and this F Overriding methods F The Object Class F Modifiers: protected, final.
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
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.
Interfaces and Inner Classes
Side effects A side effect is anything that happens in a method other than computing and/or returning a value. Example: public class hello { public int.
Interfaces F What is an Interface? F Creating an Interface F Implementing an Interface F What is Marker Interface?
1 Interface Design. 2 concept An interface is a way to describe what classes should do, without specifying how they should do it. It’s not a class but.
CS2 Module 26 Category: OO Concepts Topic: Interfaces Objectives –Interfaces.
Today’s lecture Review of chapter 8 Go over examples.
1 Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Chapter 13 Interfaces and Inner Classes Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
Inheritance and Polymorphism
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Interfaces Are used to model weak inheritance relationships Object-inheritance.
Slides prepared by Rose Williams, Binghamton University ICS201 Lecture 7 : Interfaces King Fahd University of Petroleum & Minerals College of Computer.
Lecture 5:Interfaces and Abstract Classes Michael Hsu CSULA.
9.1 CLASS (STATIC) VARIABLES AND METHODS Defining classes is only one aspect of object-oriented programming. The real power of object-oriented programming.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
Lecture 6:Interfaces and Abstract Classes Michael Hsu CSULA.
Geoff Holmes and Bernhard Pfahringer COMP206-08S General Programming 2.
2-Oct-16 Basic Object-Oriented Concepts. 2 Concept: An object has behaviors In old style programming, you had: data, which was completely passive functions,
Lecture 5:Interfaces and Abstract Classes
Web Design & Development Lecture 9
Inheritance and Polymorphism
Interfaces Professor Evan Korth.
Section 11.1 Class Variables and Methods
Abstract Classes.
Lecture 4: Interface Design
Introduction interface in Java is a blueprint of a class. It has static constants and abstract methods only. An interface is a way to describe what classes.
Chapter 14 Abstract Classes and Interfaces
Interfaces.
Chapter 13 Abstract Classes and Interfaces Part 01
CIS 110: Introduction to computer programming
Presentation transcript:

CS 61B Data Structures and Programming Methodology July 2, 2008 David Sun

Announcements Project 1 spec and code is available on the course website. Due July 15 th. Start early! Midterm I is next Wed in class from 11:00 – 1:00p.m. Open book: lecture notes, lab notes, but no laptop!

Today Constants Preventing Inheritance Abstract Classes Interfaces

Static Fields and Methods class Parent { int x = 0; static int y = 1; static void f() { System.out.printf "Ahem!%n"); } static int f(int x) { return x+1; } class Child extends Parent { String x = "no"; static String y = "way"; static void f() { System.out.printf ("I wanna!%n"); } Child dave = new Child(); Parent pDave = dave; dave.x => nopDave.x => 0 dave.y => waypDave.y => 1 dave.f() => ?pDave.f() = ? dave.f(1) => ?pDave.f(1) => 2 Fields hide inherited fields of same name; static methods hide methods of the same signature.

Constants Adding final in front of a variable means that the value of the variable can never be changed. – You must initialize the value of the final variable when it is declared. – Use final variables to create constants. class Math { public static final double PI = …; } public class System { public static final PrintStream out = … ; }

Constants (cont.) Numerical values that are used repeatedly should be turned into a final constant. if (month == 3) {...} //BAD public static final int MARCH = 3; if (month == MARCH) {... } Not all constants need to be static. – For an array x, x.length is a final field.

Preventing Inheritance A class declared to be final cannot be extended by others final class Executive extends Manager{ } A method declared final cannot be overriden by subclasses – All methods in a final class are automatically final class Employee { … public final String getName() { return name; } … }

Abstract Classes As we move up the inheritance hierarchy, classes become more general or more abstract. At the some point, the ancestor class becomes so general that it becomes a basis for other classes rather than a class with specific instances that you want to create. Such ancestor classes are declared to be abstract. Their sole purpose is to be extended.

Example StudentEmployee Human Some attributes and methods make sense for every human, and these can be factored out into the Human class. public class Human {... private int age; private String name; public int getAge() { return age}; public String getName() { return name};... }

Example (cont.) public class Human {... public String introduce() {...} //how should we code this? } Student david = new Student(... ); david.introduce(); //”I’m David and I major in Computer Science” Employee wendy = new Employee(... ); wendy.introduce(); //”I’m Wendy I work for Google” The Human class knows nothing about the person except the name and age. We can try: public String introduce() { return “”; } A better way: public abstract String introduce(); //no implementation required

Abstract Class public abstract class Human { private String name; public Human(String n); public String getName() { return name; } public abstract String introduce(); } Any class with one or more abstract methods must be declared as abstract. abstract classes can have concrete data and methods. abstract methods act as placeholders for methods that are implemented in subclasses.

public abstract class Human { private String name;... public abstract String introduce(); } public class Student extends Human{ private String major; public student(String name, String major) {...} public String introduce() { return “I’m “ + name + “and I major in” + major; } public class Employee extends Human{ private String company; public student(String name, String company) {...} public String introduce() { return “I’m “ + name + “and I work for ” + company; }

Rules for abstract Classes The concrete classes Student and Employee must implement the abstract method introduce(). – The compiler will generate an error if you don’t. If you extend an abstract class without implementing an abstract method, the subclass must be declared as abstract. You can create a variable of an abstract class: Human student; //OK You cannot create an object of an abstract class: //Compile time ERROR! Human student = new Human(“David”); //OK! Human student = new Student(“David”); student.introduce();

Human[] human = new Human[2]; human[0] = new Employee(... ); human[1] = new Student(... ); for (int i = 0; i < human.length; i++) { human[i].introduce(); } The call human[i].introduce(); is well defined because human[i] never refers to an object of the abstract human class, it must refer to a concrete subclass. Example

What are Interfaces? Describing what classes should do, without specifying how they would do it. Think of it as a contract for a set of classes. “If your class conforms to the requirements set in this contract (or this interface), then I’ll perform these services for the objects of your class”

Example The sort method of the Array class promises to sort an array of objects, but under one condition: the objects in the array must implement the Comparable interface: public interface Comparable { int compareTo(Object other); } Like an abstract method, no implementation is provided

Example public interface Comparable { int compareTo(Object other); } public class Employee implements Comparable { public int compareTo(Object other) {... } The Employee class must implement the compareTo method. i.e., define a method named compareTo that takes an Object and returns an int.

compareTo When we call x.compareTo(y), the method returns an indication whether x or y is larger: – return a negative number if y is larger – a positive number if x is larger, – zero otherwise. Suppose we want to sort by salary: public class Employee implements Comparable { public int compareTo(Object other) { Employee otherEmployee = (Employee) other; if (salary < otherEmployee.salary) return -1; if (salary > otherEmployee.salary) return 1; return 0; } }

Example

compareTo If the objects are not equal, it does not matter what negative or positive value your return. For instance, to sort by employee ID number: //negative if the first ID is less than the other, //0 if they are the same; //some positive value otherwise. return id – other.id; The subtraction trick works only for integers: salary – other.salary can round to 0 if the salaries are close enough.

Comparable An interface to describe Objects that have a natural order on them, such as String and Integer. Might use in a general-purpose max function: /** The largest value in array A, or null if A empty. */ public static Comparable max (Comparable[] A) { if (A.length == 0) return null; Comparable result = A[0]; for (int i = 1; i < A.length; i += 1) if (result.compareTo(A[i]) < 0) result = A[i]; return result; } Now max(S) will return maximum value in S if S is an array of Strings, or any other kind of Object that implements Comparable.

Properties of Interfaces Interfaces are not classes, you can’t construct objects: x = new Comparable( … ); //ERROR You can declare interface variables: Comparable x; //OK An interface variable must reference an object of a class that implements the interface. x = new Employee(…); //OK

Properties of Interfaces All methods in an interface are automatically public. – int compareTo(Object other); was not explicitly declared to be public. The implementation in Employee class must be public int compareTo(Object other); otherwise the compiler will complain. All fields in are automatically public static final. – Interfaces can contain only constants, never instance variables.

Extending Interfaces You can extend interfaces to go from greater degree of generality to a greater degree of specialization. Example: Java Collections Framework public interface Set extends Collection{...}

Interfaces and Abstract Classes abstract class Comparable { public abstract int compareTo(Object other); } public class Employee extends Comparable { int compareTo(Object other) {... } } public class Employee extends Human, Comparable //ERROR public class Employee extends Human implements Comparable //OK A class can have one and only one superclass.

Implement Multiple Interfaces interface Readable { Object get(); } interface Writeable { void put (Object x); } class Source implements Readable { Object get() {...} } void copy (Readable r, Writeable w) { w.put(r.get()); } class Sink implements Writeable { void put (Object x) {... } } class Variable implements Readable, Writeable { Object get() {...} Object put() {...} }

Using Interfaces and Abstract Class Example

The Java Collections Framework

Next Lecture Readings: – Head First Java, Chapter 7