Inheritance Sections 8.4, 8.1.

Slides:



Advertisements
Similar presentations
Big Ideas behind Inheritance. Can you think of some possible examples of inheritance hierarchies?
Advertisements

INTERFACES IN JAVA 1.Java Does not support Multiple Inheritance directly. Multiple inheritance can be achieved in java by the use of interfaces. 2.We need.
CS 106 Introduction to Computer Science I 04 / 11 / 2008 Instructor: Michael Eckmann.
Java Inheritance. What is inherited A subclass inherits variables and methods from its superclass and all of its ancestors. The subclass can use these.
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 04 / 16 / 2010 Instructor: Michael Eckmann.
CS 106 Introduction to Computer Science I 11 / 15 / 2006 Instructor: Michael Eckmann.
Building Java Programs Inner classes, generics, abstract classes reading: 9.6, 15.4,
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter N - 1 Chapter 13 Polymorphism is-a relationships Interfaces.
Inheritance and Class Hierarchies Ellen Walker CPSC 201 Data Structures Hiram College.
1 Object-Oriented Software Engineering CS Interfaces Interfaces are contracts Contracts between software groups Defines how software interacts with.
Inheritance. Inheritance Early programmers often wrote code very similar to existing code Example: A human resources system might handle different types.
COP 2800 Lake Sumter State College Mark Wilson, Instructor.
Inheritance - Polymorphism ITI 1121 Nour El Kadri.
10-Nov-15 Java Object Oriented Programming What is it?
Data Structures Using Java1 Chapter 2 Inheritance and Exception Handling.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
CSC1401 Classes - 2. Learning Goals Computing concepts Adding a method To show the pictures in the slide show Creating accessors and modifiers That protect.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
COP3502 Programming Fundamentals for CIS Majors 1 Instructor: Parisa Rashidi.
CSE 143 Lecture 20 Abstract classes. 2 Circle public class Circle { private double radius; public Circle(double radius) { this.radius = radius; } public.
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
CreatingClasses-SlideShow-part31 Creating Classes part 3 Barb Ericson Georgia Institute of Technology Dec 2009.
Creating a GUI Class An example of class design using inheritance and interfaces.
CS2102: Lecture on Abstract Classes and Inheritance Kathi Fisler.
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 / 71 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 4 Programming Fundamentals using Java 1.
Interfaces, Abstract Classes, and Polymorphism. What Is an Interface? An interface is the set of public methods in a class Java provides the syntax for.
1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
Interfaces, and Polymorphism Sections 8.4, 8.1. Outcomes n Create a polymorphic function for Lists  and other interfaces n Recognize, write, and implement.
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
Lecture 5:Interfaces and Abstract Classes
Lecture 8 D&D Chapter 9 Inheritance Date.
Advanced Programming in Java
Modern Programming Tools And Techniques-I
Inheritance ITI1121 Nour El Kadri.
Chapter 11 Inheritance and Polymorphism
Inheritance and Polymorphism
A tree set Our SearchTree class is essentially a set.
Advanced Programming in Java
Chapter 5 Hierarchies IS-A associations superclasses subclasses
Road Map Inheritance Class hierarchy Overriding methods Constructors
Inheritance "Question: What is the object oriented way of getting rich? Answer: Inheritance.“ “Inheritance is new code that reuses old code. Polymorphism.
CS 302 Week 11 Jim Williams, PhD.
CS 106A, Lecture 22 More Classes
CS2102: Lecture on Abstract Classes and Inheritance
Lesson 2: Building Blocks of Programming
Chapter 9 Inheritance and Polymorphism
CS1316: Representing Structure and Behavior
Extending Classes.
Java Programming Language
Chapter 9: Polymorphism and Inheritance
CS1316: Representing Structure and Behavior
A tree set Our SearchTree class is essentially a set.
Fundamental Error Handling
Inheritance and Polymorphism
Barb Ericson Georgia Institute of Technology Oct 2005
Java Inheritance.
Chapter 14 Abstract Classes and Interfaces
Chapter 11 Inheritance and Polymorphism
CS 200 More Classes Jim Williams, PhD.
Chapter 11 Inheritance and Polymorphism Part 1
Final and Abstract Classes
Barb Ericson Georgia Institute of Technology Oct 2005
Chapter 11 Inheritance and Encapsulation and Polymorphism
Throwing, Catching Defining
CIS 110: Introduction to computer programming
CS 240 – Advanced Programming Concepts
Presentation transcript:

Inheritance Sections 8.4, 8.1

Outcomes Use inheritance to extend interfaces Use inheritance to add methods to an existing class Override inherited methods such as toString and equals

Interface Tell Java that group of actions goes together name the group of actions say what the actions are do not say how to do them different kinds of things may do them different ways public interface Measurable { public double getArea(); public double getPerimeter(); } See Measurable.java

Implementing Interfaces It’s not enuf to just have the methods need to tell Java that we have the methods Done in the class declaration an implements clause public class Circle implements Measurable { … } public class Rectangle implements Measurable { … } tells Java they have getArea & getPerimeter don’t lie! Java will catch you out

Implementing Multiple Interfaces Can implement more than one interface list interfaces, separated by commas public class MultiPurpose implements InterA, InterB {...} public class Yikes implements IA, IB, IC, IDa, IDb {...} Must define every method from every interface it implements no lying!

Knowing More Consider this interface: public interface Polygonal { public double getArea(); public double getPerimeter(); public int getNumberOfSides(); } has all Measurable’s methods, plus one more but Java won’t recognize it as a Measurable have to say implements Polygonal, Measurable

Extending Interfaces Classes that implement Polygonal also implement Measurable can tell Java that: public interface Polygonal extends Measurable { public int getNumberOfSides(); } extends = has all of that (and more!!!) Measurable has getArea and getPerimeter so Polygonal has them, too! See Polygonal.java

Implementing Polygonal Anything that implements Polygonal must define all the methods mentioned in Polygonal interface... public int getNumberOfSides() ...plus all those mentioned in Measurable public double getArea() public double getPerimeter()

And So On... Can extend an interface that extends another just adding more methods to implement public interface RegularPolygonal extends Polygonal {...} Can extend more than one interface again, adding more methods to implement public interface FiniteSurface extends Measurable, Colourable { ... } Measurable Colourable Polygonal FiniteSurface RegularPolygonal See them!

Combining Interfaces When one interface extends two others... (or more than two others) ...it may not need any more methods it just puts those two (or more) interfaces together use empty braces (no new methods required) public interface FiniteSurface extends Measureable, Colourable {}

Exercise What methods must these classes implement? public interface IA {public void is();} public interface IB {public int howMany();} public interface IC extends IB {public String whatKind();} public interface ID extends IA, IC {} public interface IE extends IA, IB {public void what();} public class A implements IE {...} public class B implements ID {...} public class C implements IA, IB {...}

Interface Summary An interface is a data type variables can have that data type including (especially) parameters for methods such variables (methods) called polymorphic An interface lists public methods each implementing class implements them each class has its own implementation all the classes have in common is that they know how to do those things

Different or Same? Each class has its own implementation But what if some methods are implemented the same way for every class? e.g. every getName method is same for Person, Student, Faculty, Staff, Administrator, … Do we have to write that code over and over and over and over …?

Repeated Code Write classes for: Person Student Undergraduate has a name write constructors, getter, setter, toString, … Student has a name and a student number write constructors, getters, setters, toString, … Undergraduate has a name, student number, year/level GraduateStudent getName() setName(String newName) getName() setName(String newName) getName() setName(String newName) getName() setName(String newName)

“Is-a” Hierarchy Every student is a person Every professor is a person Every undergrad is a student Every grad student is a student Every professor is a person Also called an inheritance hierarchy.

Inheritance in Java Tell Java that every Student is a Person that every Professor is a Person that every Undergrad is a Student Then Java lets Students use Person methods without having to write them again! public class Person { … public String getName() … } public class Student extends Person { … } public class Professor extends Person { … } public class Undergrad extends Student { … } Same word we use to tell Java that Polygonal has every Measurable method!

Inheritance in Java public class Person { private String name; public void setName(String n) { this.name = n; } public String getName() { return this.name; } } public class Student extends Person { public void sayName() { System.out.println(“My name is ” + this.getName()); We say: - Student is a subclass of Person - Person is a superclass of Student Student s = new Student(); s.setName(“Fred”); s.sayName(); My name is Fred Each Student object has a getName method and a setName method, even tho’ it didn’t (explicitly) say it did!

Inheritance and Private Fields public class Person { private String name; public void setName(String n) { this.name = n; } public String getName() { return this.name; } } public class Student extends Person { public void sayName() { System.out.println(“My name is ” + name); Student has a name, BUT must use its getName method to get it! Even tho’ each Student object has a name, it’s not allowed to talk about it! It’s private to Person! DO NOT give Student a name field! It’d “hide” the real name field.

Calling Subclass Methods When you call a subclass method… Student s = new Student(); s.setName(“Fred”); s.sayName(); starts looking for the method in the subclass only checks superclass if not found in subclass setName not found in Student.java setName found in Person.java Sets name to “Fred” (Person can set name) sayName found in Student.java calls getName – not found in Student.java getName found in Person.java returns “Fred” (Person can talk about name!)

Exercise Create a new class SortableStringList that does everything an ArrayList<String> does, but also has a sort method of its own. SortableStringList ssl = new SortableStringList(); ssl.add(“Ten”); ssl.add(“Twenty”); ssl.add(“Thirty”); ssl.sort(); System.out.println(“ssl sorted is ” + ssl); it’s really very easy! the object you want to sort is this object! ssl sorted is [Ten, Thirty, Twenty]

Inheritance and Extra Fields Subclass can add fields as well as methods just declare them and add getters/setters public class Student extends Person { private int grade; public void setGrade(int n) { grade = n; } public int getGrade() { return grade; } public void sayName() { System.out.println(“My name is ” + getName()); }

Changed Methods Sub gets every public method from Super but doesn’t have to stick with it! can replace inherited method’s implementation just say what the new implementation is add @Override annotation public class SubClass extends SuperClass { public void sayValue() { Sopln(“My value is ” + this.getValue()); } @Override public String getValue() { return “Ba-ba”;} } SubClass c = new SubClass(); c.setValue(“Fred”); c.sayValue(); My value is Ba-ba

Overriding Inherited Methods Still inherits the changed method use super.methodName to get inherited version compare this.methodName public class SubClass extends SuperClass { public void sayValue() { Sopln(“My value is ” + this.getValue()); } @Override public String getValue() { return super.getValue().replace(‘r’,’w’); } super.getValue is SuperClass’s version of getValue it returns “Fred” replace(‘r’,’w’) changes that to “Fwed” } SubClass c = new SubClass(); c.setValue(“Fred”); c.sayValue(); My value is Fwed

Inheritance and Constructors Each SubClass object has a SuperClass part When we construct a SubClass object, we need to construct the SuperClass part call parent constructor using super(…) public class Person { private String name; public Person(String n) { name = n; } … } public class Student extends Person { public Student(String n) { super(n); … } … new Student(“Fred”)  new Person(“Fred”)  name = “Fred”

Inheritance and Constructors Can do more than just super(…), but super(…) must come first recall: constructor’s job is to set all IVs public class Student extends Person { private int grade; public Student(String n, int g) { super(n); // sets name in Person grade = g; // sets grade in Student } …

Inheritance and Polymorphism If a method asks for a superclass object… public static void printName(Person p) { … } …a subclass object is fine Student s = new Student(“Fred”); printName(s); Just like interfaces SubClass has all the methods SuperClass has so SubClass can do anything SuperClass can so SubClass can be used where SuperClass needed

Inheritance and Polymorphism If a method asks for a subclass object… public static void printGrade(Student s) { … } …a superclass object will not do Person p = new Person(“Geety”); printGrade(p); SubClass has all SuperClass methods SuperClass doesn’t have SubClass methods so SuperClass cannot replace SubClass

More Inheritance You can extend a class that extends another Undergrad extends Student extends Person as many levels as you need/want! Student inherits all Person’s public methods Undergrad inherits all Student’s public methods including the ones it inherited from Person In fact, in Java, every class extends Object even if you don’t say it does!

Inheritance Hierarchies Java uses inheritance (and interfaces) lots for example, ArrayList: java.util Class ArrayList<E> java.lang.Object java.util.AbstractCollection<E> java.util.AbstractList<E> java.util.ArrayList<E> All Implemented Interfaces: Serializable, Cloneable, Iterable<E>, Collection<E>, List<E>, RandomAccess Direct Known Subclasses: AttributeList, RoleList, RoleUnresolvedList ArrayList extends AbstractList extends AbstractCollection extends Object. implements Serializable, Cloneable, Iterable, Collection, List, RandomAccess. AttributeList, RoleList, RoleUnresolvedList all extend ArrayList.

The Object Class Every class extends Object even if it doesn’t say so public class Person  public class Person extends Object Every class inherits Object’s methods including its implementations Object’s methods include toString which we @Override in our own classes because Object’s implementation is not very nice

Overriding toString Nice to do for any class you create so prints something nicer than Circle@9304b1 We already covered this! public class Circle { @Override public String toString() { return “Circle (r = ” + radius + “)”; } … } Circle c = new Circle(5.2); System.out.println(c); Circle (r = 5.2)

The equals Method Another Object method is equals public boolean equals(Object other) expects to be given an Object equals is a useful method but Object’s implementation not so useful just uses == need to @Override it to make it better just like String does!

Overloading equals Don’t do this! it’s not overriding Object’s equals public boolean equals(Circle other) { return this.radius == other.radius; } it’s not overriding Object’s equals @Override your code might sometimes do the wrong thing!

Overriding equals equals takes an Object check if other is a same class (using instanceof) if so, compare their fields @Override public boolean equals(Object obj) { if (obj instanceof Circle) { // if obj is a Circle Circle c = (Circle) obj; // make a circle variable return c.radius == this.radius; // compare the radiusses } return false; // not equals to non-Circles

Exercise Write an equals method for Rectangle class equals if have same length and width remember: public class Rectangle implements Measurable { private double length, width; public Rectangle(double l, double w) { length = l; width = w; } public double getLength() { return length; } public double getWidth() { return width; } @Override public double getArea() { return length * width; } @Override public double getPerimeter () { return 2 * (length + width); } }

Exception Classes Exceptions form an inheritance hierarchy (Lots more than I’m showing you here!) Exception IOException RuntimeException FileNotFoundException NoSuchElementException IndexOutOfBoundsException InputMismatchException ArrayIndexOutOfBoundsException StringIndexOutOfBoundsException

Exception Classes Some of our exceptions extend others InputMismatchEx. extends NoSuchElementEx. Thus can use IME wherever NSEE needed including in a catch block! catch (NoSuchElementException nsee) { System.out.println(nsee); } NSEE catch block catches IMEs! NoSuchElementException InputMismatchException java.util.InputMismatchException: What???

Ordering Catch Blocks If IME needs different handling than NSEE, then catch IME before NSEE try { … } catch (InputMismatchException ime) { } catch (NoSuchElementException nsee) { } if you reverse them, compiler will complain that the IME has “already been caught”

Creating Your Own Exceptions Can create classes to represent errors e.g. InvalidGradeException for Student class Extend RuntimeException or extend Exception, but then need throws clauses add constructor(s) public class InvalidGradeException extends RuntimeException { // @param g the invalid grade (will be changed to String) public InvalidGradeException(int g) { super(Integer.toString(g)); } … }

Creating Your Own Exceptions Create at least two constructors one with (String msg); other with () public class InvalidGradeException extends RuntimeException { public InvalidGradeException() { super(); } public InvalidGradeException(String msg) { super(msg); } // @param g the invalid grade (will be changed to String) public InvalidGradeException(int g) { super(Integer.toString(g)); } } don’t need any other methods but can add more if they’d be helpful

Throwing Your Own Exceptions If you detect the error condition: create and throw the new exception object if (!isValidGrade(newGrade)) { throw new InvalidGradeException(newGrade); } isValidGrade checks if grade is valid throw is the command to throw something new … creates the new exception object InvalidGradeException constructor is told the grade

Throw vs. Throws Throw is a command: Throw the rock! Throws is a statement: Joe throws rocks. Throw tells computer to throw (something) if (isAngry()) { throw new Rock(); } Throws tells computer that (something) could get thrown public void joe() throws Rock { … } “throws”  “could throw a”

Exercise Write a new exception class NotEnufSleepException allow client to specify how many hours of sleep they got, as a double value

Next Week Next week we will start putting inheritance and polymorphism to good use! we’re going to learn how to make a GUI public class MyGUI extends JFrame implements ActionListener { JFrame is a window class; MyGUI is a JFrame thus MyGUI is a window class MyGUI knows how to listen for actions like, for example, if a button gets clicked

Bonus Material: Abstract Classes Abstract classes are classes... uses “class” not “interface” public abstract class AbstractList ... ...but don’t implement every method... some methods declared abstract—no body public abstract void get(int index); ...so class can’t be instantiated AbstractList<String> abs = new AbstractList<String>(); half-way between classes & interfaces

Use of Abstract Classes Know how to do some, but not all, methods public abstract void dontKnowThis(); public void doKnowThat() { … } public void knowThisToo() { … } Known method calls unknown method public void doKnowThat() { knowThisToo(); dontKnowThis(); } every subclass will override dontKnowThis but will use doKnowThat from the parent class

Abstract Game Player Human and non-human players human/computer choose move differently but executing move is the same! public abstract class AbstractPlayer { public void playTurn() { Move m = chooseMove(); // abstract executeMove(m); // NOT abstract } public abstract Move chooseMove(); public void executeMove(Move m) { … } … AbstractPlayer HumanPlayer ComputerPlayer (each define chooseMove())

Exercise Create an abstract class named AbsClass with methods: doThis, doThat (both abstract) doTheOther (prints “Hey, what?”) doItAll (calls all three of above, in that order) Create two subclasses with distinct implementations of doThis and doThat