Abstract Classes We often define classes as subclasses of other classes – First, define the superclass – In some cases, a superclass may not have enough.

Slides:



Advertisements
Similar presentations
Chapter 13 Abstraction and inheritance. This chapter discusses n Implementing abstraction. u extension u inheritance n Polymorphism/dynamic binding. n.
Advertisements

Object Oriented Programming with Java
Inheritance. Many objects have a hierarchical relationship –Examples: zoo, car/vehicle, card game, airline reservation system Inheritance allows software.
Reusable Classes.  Motivation: Write less code!
CS 106 Introduction to Computer Science I 04 / 11 / 2008 Instructor: Michael Eckmann.
Inheritance Inheritance Reserved word protected Reserved word super
Java Inheritance. What is inherited A subclass inherits variables and methods from its superclass and all of its ancestors. The subclass can use these.
SE-1020 Dr. Mark L. Hornick 1 Inheritance and Polymorphism: Abstract Classes The “not quite” classes.
CS 106 Introduction to Computer Science I 11 / 26 / 2007 Instructor: Michael Eckmann.
More about classes and objects Classes in Visual Basic.NET.
Inheritance. Extending Classes It’s possible to create a class by using another as a starting point  i.e. Start with the original class then add methods,
CS 106 Introduction to Computer Science I 11 / 28 / 2007 Instructor: Michael Eckmann.
CS 106 Introduction to Computer Science I 11 / 20 / 2006 Instructor: Michael Eckmann.
CS 106 Introduction to Computer Science I 04 / 16 / 2010 Instructor: Michael Eckmann.
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.
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
UML Class Diagram: class Rectangle
Abstract Classes b b An abstract class is a placeholder in a class hierarchy that represents a generic concept b b An abstract class cannot be instantiated.
Chapter 6 Class Inheritance F Superclasses and Subclasses F Keywords: super F Overriding methods F The Object Class F Modifiers: protected, final and abstract.
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
Features of Object Oriented Programming Lec.4. ABSTRACTION AND ENCAPSULATION Computer programs can be very complex, perhaps the most complicated artifact.
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
Mark Fontenot CSE Honors Principles of Computer Science I Note Set 14.
Chris Kiekintveld CS 2401 (Fall 2010) Elementary Data Structures and Algorithms Inheritance and Polymorphism.
These materials where developed by Martin Schray. Please feel free to use and modify them for non-commercial purposes. If you find them useful or would.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
Abstract Classes. Review PA – 3 Design Considerations /Web/CS239/programs/pa3/draft.php ?harrisnlCS239
Java Programming Dr. Randy Kaplan. Abstract Classes and Methods.
8. Inheritance “Is-a” Relationship. Topics Creating Subclasses Overriding Methods Class Hierarchies Abstract Class Inheritance and GUIs The Timer Class.
Inheritance. Inheritance is a fundamental object-oriented design technique used to create and organize reusable classes Chapter 8 focuses on: deriving.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Programming With Java ICS201 University Of Ha’il1 Chapter 7 Inheritance.
Object Oriented Programming
Chapter 7: Class Inheritance F Superclasses and Subclasses F Keywords: super and this F Overriding methods F The Object Class F Modifiers: protected, final.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Coming up: Inheritance
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 – 9.4.
Object Oriented programming Instructor: Dr. Essam H. Houssein.
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
(c) University of Washington06-1 CSC 143 Java Inheritance Tidbits.
Object orientation and Packaging in Java Object Orientation and Packaging Introduction: After completing this chapter, you will be able to identify.
1 / 41 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 5 Programming Fundamentals using Java 1.
CSI 3125, Preliminaries, page 1 Inheritance. CSI 3125, Preliminaries, page 2 Inheritance Using inheritance, can create a general class that defines traits.
1 Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
POLYMORPHISM Chapter 6. Chapter Polymorphism  Polymorphism concept  Abstract classes and methods  Method overriding  Concrete sub classes and.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Outline Creating Subclasses Overriding Methods Class Hierarchies Inheritance.
Inheritance & Method Overriding BCIS 3680 Enterprise Programming.
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.
Lecture 5:Interfaces and Abstract Classes Michael Hsu CSULA.
Notices Assn 2 is due tomorrow, 7pm. Moodle quiz next week – written in the lab as before. Everything up to and including today’s lecture: Big Topics are.
 The word static is used to declare either a ________ variable or method.  Why do we use statics?  What is Polymorphism? class In general, we use a.
Lecture 6:Interfaces and Abstract Classes Michael Hsu CSULA.
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
1 More About Derived Classes and Inheritance Chapter 9.
Lecture 12 Inheritance.
Inheritance and Polymorphism
Agenda Warmup AP Exam Review: Litvin A2
UML Class Diagram: class Rectangle
Lecture 14 - Abstract Classes
Class Inheritance (Cont.)
OBJECT ORIENTED PROGRAMMING II LECTURE 8 GEORGE KOUTSOGIANNAKIS
Polymorphism CT1513.
Week 6 Object-Oriented Programming (2): Polymorphism
Abstract Classes Page
Java Inheritance.
Chapter 14 Abstract Classes and Interfaces
Chapter 8 Class Inheritance and Interfaces
Presentation transcript:

Abstract Classes We often define classes as subclasses of other classes – First, define the superclass – In some cases, a superclass may not have enough specificity to allow for an implementation of one or more methods a GeometricObject class might be the parent for Circle and Rectangle computeArea and computePerimeter are two useful methods for these subclasses but GeometricObject is too generic of a class to be able to implement these methods on yet we want to define these methods in GeometricObject so they are inherited by Circle and Rectangle recall we did something similar when implement Vehicle so that other Vehicle subclasses could inherit getBattleUtility An abstract method is a definition for a method without an implementation An abstract class is a class that contains at least one abstract method

Abstract Classes You cannot instantiate an object of an abstract class (although you can declare a variable to be of that type for polymorphism) – Here we see obj is a GeometricObject – We cannot instantiate obj to be a GeometricObject but we can instantiate it to be a Circle or a Rectangle GeometricObject obj; obj = new Circle(10); … obj = new Rectangle(5,10); The reason for having abstract classes is first to provide a “placeholder” that informs programmers of what needs to be implemented in a subclass and second to provide a common basis for all subclasses of this superclass

Defining an Abstract Class Add the word abstract to the class header –public abstract class Name You can define instance data, constants and methods as normal – You can also implement at least one abstract method (you do not have to have abstract methods in an abstract class) To declare an abstract method – Place the word abstract in the method header – In place of the method’s implementation {…} just put a ; public abstract void foo(…); – The method’s profile (return type, parameters) must be exactly as you expect subclasses to implement them you must override an abstract method, it can not be overloaded you cannot make an abstract method static The example that follows is the UML for GeometricObject, Circle and Rectangle

Some Comments Abstract methods cannot be placed in non-abstract classes – If a class extends an abstract class, it must either implement all inherited abstract methods or itself also be abstract – Recall that you cannot instantiate an object of an abstract class An abstract class does not need to contain abstract methods – You would only do this if the superclass was merely a base for other classes to inherit from A subclass can override a parent class’ method and make it abstract – in which case the subclass would have to be abstract – Here the superclass is not [necessarily] abstract while the subclass is – This is unusual but allows you to “shut off” inheritance of a superclass implementation of a method

Example: Revising Vehicle public abstract class Vehicle { protected String type; protected boolean heavilyArmored; protected int capacity; protected int speed; protected int armament; public Vehicle(String t) {... } public String getType() {...} public boolean getHeavilyArmored() {...} public int getCapcity() {...} public int getSpeed() {...} public int getArmament() {...} public String toString() {...} public abstract int getBattleUtility (boolean night, boolean roughTerrain, boolean needGroundSupport, boolean needHeavyArms, boolean antiAircraftGuns, boolean equipment, int distance); } As before abstract and no implementation

Another Example We want to define a deck of cards – There are different types of cards Ordinary cards which are shuffled randomly Magic cards which are not shuffled randomly Stacked decks We will define CardClass to represent an abstract deck of cards – This class will create instance data of the deck itself (an array of ints which indicate the order of the cards currently) and whether a particular card has been dealt yet (a boolean array) – Non-abstract methods will be a constructor and accessors to get a card and determine if a card has been dealt – But the shuffle method will be abstract based on the subclass We will then implement a subclass, PlayingCards to be a deck of ordinary playing cards – The shuffle method is implemented as a simple random generation of the sequence of cards (numbers 0-51)

public abstract class CardClass { protected int[] deck; protected boolean[] dealt; public CardClass() { deck=new int[52]; dealt=new boolean[52]; for(int i=0;i<52;i++) dealt[i]=false; } public boolean dealtYet(int index) throws IndexOutOfBoundsException{ if(index<52) return dealt[index]; else throw new IndexOutOfBoundsException(index + " is too large for the size of this deck"); } public int getCard(int index) throws IndexOutOfBoundsException { if(index<52) return deck[index]; else throw new IndexOutOfBoundsException(index + " is too large for the size of this deck"); } public abstract void shuffle(); }

import java.util.*; public class PlayingCards extends CardClass { protected Random g; public PlayingCards() { super(); g=new Random(); } public void shuffle() { boolean[] order=new boolean[52]; int i, temp; for(i=0;i<52;i++) order[i]=false; for(i=0;i<52;i++) { do { temp=g.nextInt(52); }while(order[temp]); order[temp]=true; deck[i]=temp; }

Arrays of an Abstract Class You cannot instantiate an abstract class But you can create an array of an abstract class and instantiate the individual array elements to be subclasses – Assume we have our previously described GeometricShape, Circle and Rectangle classes –GeometricShape[ ] shapes = new GeometricShape[10]; This is legal –shapes[0] = new Circle(10); –shapes[1] = new Rectangle(5, 10); These are legal –Shapes[2] = new GeometricShape( ); This is illegal because GeometricShape is abstract

Interfaces Java does not permit multiple inheritance (inheriting from multiple classes) but it does provide interfaces – In a way, interfaces are a form of multiple inheritance An interface is like an abstract class in that it defines a portion of a class but does not implement it – The interface class contains constants and abstract methods only, no implemented methods and no instance data – By implementing an interface, like extending an abstract class, you are completing the class – The advantage of implementing an interface is that you are stating that the given class will act a certain way so that other classes can expect a particular functionality for instance, you might implement Comparable indicating that the class will implement comparesTo

Implementing an Interface You add to the class header implements InterfaceName Now you must override the abstract method(s) defined in the Interface – If you do not override all of the abstract methods, you will receive compilation errors – You cannot instantiate an object of a type of Interface class because of the abstract methods (just as you cannot instantiate the object of an abstract class), all you can do is implement the Interface class in your own class One of the most significant types of Interfaces is the class of GUI handlers that will respond when a GUI component, mouse, or keyboard action occurs – We will look at this later in the semester – Here, we will concentrate on two of the most significant interfaces: Comparable and Cloneable

Implementing Comparable Comparable is an interface class meaning that as a class, it is defined as an interface which means that you cannot instantiate an object of this type You also will (most likely) not extend Comparable but instead implement Comparable The reason for the Comparable interface is to indicate that a class that you are implementing will have the ability to directly compare two instances of this type – recall that the relational operators (, etc) are not available for objects, only for primitive types – so instead, we will implement Comparable which requires that we implement a method called compareTo (recall Strings have this method, the reason being that Strings implement Comparable requiring this method be implemented) How do you compare two objects? Depends on the type of object – we look at a couple of examples coming up

Continued To implement Comparable, do the following – Add implements Comparable to the class header As in public class MyClass extends YourClass implements Comparable – Add a compareTo method with the following profile public int compareTo(Object o) {…} Notice that your compareTo is receiving an Object, not a MyClass object, why? Because this is how compareTo appears as an abstract method in the Comparable class If you do not match this profile exactly then you are not overriding the abstract compareTo but instead overloading it, and so compilation will fail compareTo will return an int value: negative if this object is less than the object passed to compareTo, positive if this object is greater and 0 if the two objects are deemed equivalent

Examples Here, we make the Circle class (introduced earlier in the semester) Comparable – Circles will be compared based on their radius As an alternative to using (Object o) and downcasting as shown above, we can implement Comparable employing generics – see the next example public class Circle extends GeometricObject implements Comparable {... // as before public int compareTo(Object o) { if(radius>((Circle)o).getRadius( )) return 1; else if(radius<((Circle)o).getRadius( )) return -1; else return 0; }

Another Example: Comparing Names public class Name implements Comparable { private String first, middle, last; public Name(String f, String m, String l) { first=f;middle=m;last=l; } public String getFirst() {return first;} public String getMiddle() {return middle;} public String getLast() {return last;} public int compareTo(Name n) { if(last.compareTo(n.getLast())>0) return 1; else if(last.compareTo(n.getLast())<0) return -1; else if(first.compareTo(n.getFirst())>0) return 1; else if(first.compareTo(n.getFirst())<0) return -1; else if(middle.compareTo(n.getMiddle())>0) return 1; else if(middle.compareTo(n.getMiddle())<0) return -1; else return 0; }

Creating An Interface Class You can create your own interface classes by substituting the modifier interface in place of class –public interface InterfaceName The Interface’s definition will consist solely of constants and abstract method definitions – The abstract methods have no body (no {…}) and end with a ; Example: we have a class called Instrument to define various types of musical instruments – We want to define an interface class called Playable which, if implemented, will indicate how to play that instrument –public interface Playable { public abstract String howToPlay( ); } – Now, if we implement Playable, we have to define a howToPlay method which returns a String

Implementing Playable public class Drums extends Instrument implements Playable { private int numDrums; public Drums(int size) { super(“Drums”);// assume Instrument’s constructor assigns numDrums=size;// the var type to this String } public Drums( ) { super(“Drums”); numDrums=0; } public String howToPlay( ) { return “Strike drums with drumsticks or mallets”; } public class Guitar extends Instrument implements Playable { private int numStrings; // constructors similar to Drums public String howToPlay( ) { return “Strum strings with pick or fingers”; }

Implementing Cloneable Consider the following code –SomeObject o1, o2; –o1=new SomeObject(…); –o2=o1; In this code, o1 points at an object in heap memory that has been instantiated with the new operator, but what about o2? – Is o2 another object with the same values as o1 or is it the same object? It is the same If we instead want to “clone” o1 into o2 we would create another object, have o2 point at the new object in the heap, and set all of its values to be the same as o1 In this way, we have two different objects which are equivalent rather than two reference variables which are equal in that they are pointing at the same object We accomplish this by implementing Cloneable which requires implementing a clone method

Cloneable Interface Unlike Comparable, the Cloneable interface is empty – there is no abstract method defined – You must still implement the clone method According to the textbook, the abstract method for clone is defined as follows –protected native Object clone( ) throws CloneNotSupportedException; –native means that the actual implementation for copying data is left up to the JVM, not the compiler – Notice that clone returns an Object so you will have to cast the returned object appropriately – You must either add the “throws Clone…” to your method header or handle it in a try-catch block when you attempt to clone an object of the class you have implemented as cloneable

Example: Person Class public class Person implements Cloneable { private String name; private int age, height, weight; private boolean isMarried; private Person spouse; public Person() { age=0; name="unknown"; isMarried=false; spouse=null; } public Person(String n, int a, int h, int w) { age=a; name=n; height=h; weight=w; isMarried=false; spouse=null; }

public Person(String n, int a, int h, int w, Person s) { age=a; name=n; height=h; weight=w; isMarried=true; spouse=s; } public void getsMarried(Person s) { if(!isMarried) { isMarried=true; spouse=s; } else System.out.println(name + " cannot marry " + s.getName() + " until " + name + " gets a divorce!"); } public String getName() {return name;} public int getAge() {return age;} public int getHeight() {return height;} public int getWeight() {return weight;} public String getSpouseName() {if(isMarried) return spouse.getName(); else return "not married";}

public void setName(String n) { if(name==null) name=n;} public void setAge(int a) { if(age==0) age=a;} public void setHeight(int h) { if(height==0) height=h;} public void setWeight(int w) { if(weight==0) weight=w;} public void setMarried(Person s) { if(!isMarried) { isMarried=true; spouse=s; } public Object clone() throws CloneNotSupportedException { Person p=(Person)super.clone(); p.setName(name); p.setAge(age); p.setHeight(height); p.setWeight(weight); p.setMarried(spouse); return p; } } // ends the class

People Class public class People { public static void main(String[] args) throws CloneNotSupportedException { Person p1=new Person(); Person p2=new Person("Frank Zappa", 53, 69, 158); Person p3=new Person("Gail Sloatman", 50, 63, 110); p2.getsMarried(p3); p3.getsMarried(p2); p1=(Person)p2.clone(); System.out.println(p1.getName() + " " + p1.getAge() + " " + p1.getHeight() + " " + p1.getWeight() + " " + p1.getSpouseName()); } An alternative implementation is to remove the throws statement from main and insert the p1=(Person)p2.clone(); statement in a try block with a catch block that can catch CloneNotSupportedException

Interfaces vs Abstract Classes Both types provide a basis for the programmer to build upon – Abstract classes support single inheritance – Interfaces offer a form of multiple inheritance – Abstract classes can contain instance data and non-abstract methods – Interfaces cannot contain instance data and non-abstract methods (and can even be empty), the only variables must be constants ( public static final ) and the only methods must be public abstract – Abstract classes can have constructors, interfaces will not – Objects of either type can be declared but not instantiated An interface class can itself extend other interfaces in which case implementing that interface requires implementing all of the methods of that interface and its superclasses – A naming convention: class names are usually nouns but interface names can be nouns or adjectives (particularly if they end with “able” or “ible” such as “Comparable” or “Cloneable”)