Presentation is loading. Please wait.

Presentation is loading. Please wait.

Inheritance Sections 8.4, 8.1.

Similar presentations


Presentation on theme: "Inheritance Sections 8.4, 8.1."— Presentation transcript:

1 Inheritance Sections 8.4, 8.1

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

3 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

4 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

5 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!

6 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

7 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

8 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()

9 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!

10 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 {}

11 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 {...}

12 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

13 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 …?

14 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)

15 “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.

16 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!

17 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!

18 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.

19 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!)

20 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]

21 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()); }

22 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 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

23 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

24 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”

25 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 }

26 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

27 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

28 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!

29 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.

30 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 in our own classes because Object’s implementation is not very nice

31 Overriding toString Nice to do for any class you create
so prints something nicer than 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)

32 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 it to make it better just like String does!

33 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!

34 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

35 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); } }

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

37 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???

38 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”

39 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 { g the invalid grade (will be changed to String) public InvalidGradeException(int g) { super(Integer.toString(g)); } }

40 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); } 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

41 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

42 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”

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

44 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

45 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

46 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

47 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())

48 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


Download ppt "Inheritance Sections 8.4, 8.1."

Similar presentations


Ads by Google