Understanding Exceptions & Inheritance in Java

review of csci 1228 n.w
1 / 91
Embed
Share

Explore the concepts of exceptions, inheritance, and polymorphism in Java programming. Learn why exceptions are thrown, who throws them, what to throw, who catches them, and how to catch them. Discover exceptional circumstances, common exceptions like InputMismatchException and NoSuchElementException, preferred exceptions for specific situations, and the importance of handling exceptions effectively in Java programming.

  • Java Programming
  • Exceptions
  • Inheritance
  • Polymorphism

Uploaded on | 0 Views


Download Presentation

Please find below an Image/Link to download the presentation.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author. If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.

You are allowed to download the files provided on this website for personal or commercial use, subject to the condition that they are used lawfully. All files are the property of their respective owners.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author.

E N D

Presentation Transcript


  1. Review of CSCI 1228 Exceptions Inheritance Polymorphism

  2. Part I Exceptions why thrown who throws them what to throw who catches them how to catch

  3. Exceptional Circumstances Reading numbers from user User types in a word not the sort of thing we expected program crashes Enter a number: 20 Enter another number: done Exception in thread "main" java.util.InputMismatchException at java.util.Scanner.throwFor(Scanner.java:840) at java.util.Scanner.next(Scanner.java:1461) at java.util.Scanner.nextDouble(Scanner.java:2387) at SumNumbers.main(SumNumbers.java:26) see SumNumbers.java

  4. Exceptional Circumstances Exception was thrown by the Scanner Enter a number: 20 Enter another number: done Exception in thread "main" java.util.InputMismatchException at java.util.Scanner.throwFor(Scanner.java:840) at java.util.Scanner.next(Scanner.java:1461) at java.util.Scanner.nextDouble(Scanner.java:2387) at SumNumbers.main(SumNumbers.java:26) the nextDouble method could not finish its job did not try to guess what client would want! threw an exception to let client know see SumNumbers.java

  5. Who Throws Them Data type classes throw exceptions they are asked to do something for whatever reason they cannot do it they signal their displeasure The command to throw is throw (duh!) throw new InputMismatchException(); need to create the exception object to throw

  6. What to Throw Depends on what went wrong wrong kind of input? InputMismatchException no input there there at all? NoSuchElementException asking null a question? NullPointerException index out of bounds on an array? ArrayIndexOutOfBoundsException

  7. Preferred Exceptions for 2341 IllegalArgumentException the argument has an invalid value for example: negative height for a rectangle IllegalStateException that request is inappropriate at this time for example: putting something into a full bag NoSuchElementException for example: taking something out of an empty bag

  8. Who Catches Them The client catches them whichever class called the data type method the method that can deal with the problem in the place where it is best dealt with Never catch an exception thrown in the same method they are for telling others about a problem use if/else or similar control instead

  9. How to Catch Them Use a try-catch block try part includes the method call catch part indicates what kind of exception and deals with that problem try { num = KBD.nextInt(); // read an int value } catch (InputMismatchException ime) { sout("That is not an integer!"); KBD.next(); // delete the offending input }

  10. About the Try Block Skips from middle of try- to catch-block intervening code is not executed try { num = KBD.nextInt(); // read an int value sout("You entered " + num); sum += num; sout("The sum is now " + sum); } catch (InputMismatchException ime) { // no number reported; sum not updated; // no new sum to report!

  11. Multiple Catch Blocks There can be multiple catch blocks; as many different kinds as you can deal with try { } catch (InputMismatchException ime) { } catch (NoSuchElementException nse) { } catch (ArrayIndexOutOfBoundsException aioob) { }

  12. Combined Catch Blocks Can combine exception types use the same catch block for two or more different exception types use a single vertical bar (|) between the types try { } catch (InputMismatchException | FileNotFoundException exc) { // this code deals with both kinds of exception } catch (IOException nse) { // this code is only for IOExceptions }

  13. Part II Inheritance & polymorphism inheriting method definitions overriding method definitions constructors in subclasses preventing overriding the equals method

  14. Inheritance Inheritance a way of using code that s been written before without copying it (copying is bad) being a special version of another class a self-driving car is a special kind of car or a more specific kind of another class a Nova Scotian is a specific kind of Canadian Used extensively in OOP Object Oriented Programming

  15. Is vs. Has Inheritance is a relationship a self-driving car is a car a Nova Scotian is a Canadian Instance variable has a relationship Rectangle has a height Student has an A-number Is is not the same as Has you are a person; you do not have a person you have a kidney; you are not a kidney

  16. Declaring Inheritance Need to tell Java about inheritance my class inherits from this other class Use the extends keyword public class SelfDrivingCar extends Car { public class NovaScotian extends Canadian { public class Student extends Person { class you extend is called your superclass also called a parent class you are said to be one of its subclasses also called a child class

  17. Inheriting Public Methods public class Parent { private String value; public void setValue(String v) { this.value = v; } public String getValue() { return this.value; } } public class Child extends Parent { public void sayValue() { System.out.println("My value is " + this.getValue()); } } Each Child object has a getValue method and a setValue method, even tho it didn t (explicitly) say it did! Child c = new Child(); c.setValue("Fred"); c.sayValue(); My value is Fred

  18. Sort-of-Inheriting Fields public class Parent { private String value; public void setValue(String v) { this.value = v; } public String getValue() { return this.value; } } public class Child extends Parent { public void sayValue() { System.out.println("My value is " + value); } } Even tho each Child object has a value, it s not allowed to talk about it! It s private to the Parent class!

  19. Parents vs. Children public class Parent { private String value; public void setValue(String v) { this.value = v; } public String getValue() { return this.value; } } public class Child extends Parent { public void sayValue() { System.out.println("My value is " + this.getValue()); } } Parents do not get their children s methods! e.g.Parent objects don t have sayValue method. Parent p = new Parent(); p.setValue("Fred"); p.sayValue();

  20. Changed Methods Child gets every public method from Parent but doesn t have to stick with it! child can changethe method s implementation just say what the new implementation is this is called over-riding the inherited definition public class Child extends Parent { public void sayValue() { Sopln("My value is " + this.getValue()); } @Override public String getValue() { return "Ba-ba";} } Child c = new Child(); c.setValue("Fred"); c.sayValue(); My value is Ba-ba

  21. The toString Method @Override public String toString() toString inherited by every Java class inherited from Object the version that returns Rectangle@173F6C08 every class inherits from Object if it doesn t sayit extends anything then it extends Object the @Override says we re changing it to return something a bit more useful

  22. Over-Riding Methods Still inherits the changed method use super.methodName to get inherited version compare this.methodName public class Child extends Parent { public void sayValue() { Sopln( My value is + this.getValue()); } @Override public String getValue() { return super.getValue().replace('r', 'w'); } } super.getValue is Parent s version of getValue it returns Fred replace( r , w ) changes that to Fwed Child c = new Child(); c.setValue("Fred"); c.sayValue(); My value is Fwed

  23. More Inheritance You can extend a class that extends another Parent Child Grandchild and so on! Child inherits all Parent s public methods Grandchild inherits all Child s public methods including the ones it inherited from Parent but gets Child s versions of methods (if different) Java allows only one parent class multiple inheritance leads to complications

  24. Variable Types vs. Object Types Variables of superclass type allowed to refer to objects of subclass type Parent p1, p2; p1 = new Parent("Cora"); p2 = new Child("Fred"); // yup! Can only call variable s methods p2.sayValue(); // syntax error But uses object s definitions p2.getValue(); // returns "Fwed" p2 (Parent) p1 (Parent) & & "Cora" ("Fred")

  25. Constructors in Subclasses Recall purpose of constructor: Parent p1 = new Parent("Cora"); give values to all instance variables public class Parent { private String value; public Parent(String requestedValue) { value = requestedValue; } } Subclass needs to do that, too Child c1 = new Child("Fred"); but the value field is private to Parent!

  26. Constructors in Subclasses Need to call parent s constructor use super( ) public class Child extends Parent { public Child(String requestedValue) { super(requestedValue); } } provide all necessary arguments compare to this( ) public class Parent { private String value; public Parent(String requestedValue) { value = requestedValue; } public Parent() { this("(none)"); } // sets value to "(none)" }

  27. Recommendations Give every class a primary constructor calls primary constructor of superclass (first!) using super( ) sets all locally defined instance variables Other constructors call primary using this( ) NOTE: both super and this need to be first they can t both be first you can t do both!

  28. Notes on Constructors If you don t call super( ) or this( ), then Java will insert a call to super() the no-argument constructor for the superclass If superclass has no no-argument constructor, Java complains about subclass constructor public Child(int req) { myField = req; } constructor Parent in class Parent cannot be applied to given types

  29. Person-Student-Faculty Example Person is our base class has a name field Student extends Person has studentNumber and grade fields Undergrad extends Student has a year field GradStudent extends Student has a previousDegree field

  30. Sample Hierarchy Person has a name Person Student has an A_NUMBER and a grade Student Undergrad has a year Undergrad GradStudent has a previousDegree GradStudent

  31. Person public class Person { private String name; public Person(String reqName) { name = reqName; } public String getName() { return name; } public void setName(String newName) { name = newName; } }

  32. Student public class Student extends Person { public final String A_NUMBER; private int grade; public Student(String reqName) { super(reqName); grade = 0; A_NUMBER = nextANumber(); } public int getGrade() { return grade; } public void setGrade(int newGrade) { if (Student.isValidGrade(newGrade)) {grade = newGrade;}else{ } } private static int numStudents = 0; private static String nextANumber() { return ; } public static boolean isValidGrade(int g) { return ; } }

  33. Undergrad public class Undergrad extends Student { private int year; public Undergrad(String reqName, int reqYear) { super(reqName); year = reqYear; } public Undergrad(String reqName) { this(reqName, 1); } public int getYear() { return year; } public void setYear(int newYear) { year = newYear; } }

  34. GradStudent public class GradStudent extends Student { public final String previousDegree; public GradStudent(String reqName, String reqPrevDeg) { super(reqName); previousDegree = reqPrevDegree; } }

  35. The Object Class There is a class in Java called Object If a class has no extends clause then it extends Object our Person class extends Object So every class extends Object is a child, grandchild, great-grandchild, Every class inherits Object s methods or the modified versions its parent class has

  36. Object Methods Has 11, but we re most concerned with: toString() this is how I should be printed. equals(Object other) am I equals to other? Object definitions: toString() Class@hashcode equals(Object other): same as this == other print/println automatically uses toString(): Circle c = new Circle(5.2); Sopln(c); Circle@9304b1

  37. Over-Riding toString Nice to do for any class you create so prints something nicer than Circle@9304b1 Method returns the String to print it does not printthe String! 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)

  38. Over-Riding toString In Person: @Override public String toString() { return name; } In Student: @Override public String toString() { return getName() + " (" + A_NUMBER + ") ; } In GradStudent: @Override public String toString { return getName() + " (" + previousDegree + ") ; } Bob Djenaba (A00000002) Geety (BSc)

  39. Not Over-Riding toString Undergrad does not override toString so what s the output for an Undergrad? is it that ugly Undergrad@123456ff stuff? Use inherited version no toString in Undergrad; go to superclass find toString in Student; use it Undergrad ug = new Undergrad("Billy"); System.out.println(ug); Billy (A00000005)

  40. The equals Method Object version just uses == public boolean equals(Object obj) { return this == obj; } Want better than that Strings need to compare character by character different objects: YES answer & & but equal values: yes yes

  41. Over-Riding equals equals should expect an Object @Override public boolean equals(MyType other) { } over-loaded method, not over-ridden @Override public boolean equals(Object other) { } Can only be equals to objects of same type different kinds of objects not equals to this one need to check if the object is the same type the instanceof operator if (object instanceof MyType) { }

  42. Over-Riding equals Circles equal if they have same radius public boolean equals(Object other) { if (other instanceof Circle) { // if other is a Circle Circle that = (Circle) other; return this.radius == that.radius; } return false; } NOTE: don t need to check if other is null null instanceof Anything returns false // make a circle variable // compare the radii // not equals to nulls/non-Circles return this.radius == other.radius; // wrong

  43. Type Casting Need to ask other object about its radius can t use variable other its type is Object Object doesn t have radius or getRadius() can t even assign other into a Circle variable Circle that = other; but the object is a Circle (other instanceof Circle) is true need to tell Java it s really OK Circle that = (Circle) other; program will crash if you lied! Object cannot be converted to Circle

  44. Over-Riding equals Since Java 14 can use pattern matching public boolean equals(Object other) { if (other instanceof Circle that) { // add variable name after class return this.radius == that.radius; } return false; // not equals to nulls/non-Circles } no longer need to create and assign variable Circle that = (Circle) other; // no longer needed return this.radius == other.radius; // wrong

  45. c2.equals(c3) main r1 (Rectangle) c3 (Circle) c2 (Circle) & & & 11.0 x 3.0 radius: 5.5 radius: 5.5 equals other (Object) this (Circle) that (Circle) & & &

  46. c2.equals("(Not a Circle)") main r1 (Rectangle) c3 (Circle) c2 (Circle) & & & 11.0 x 3.0 radius: 5.5 radius: 5.5 equals other (Object) this (Circle) & &

  47. Part III Polymorphism recognize, write, and implement interfaces make a class sortable by implementing the Comparable<> interface add different ways of sorting by implementing the Comparator<> interface understand the significance of a SAM Single Abstract Method interface

  48. Variables and Objects Recall that supertype variables can refer to subtype objects used primarily in parameters public static void sayHiTo(Person p) { sout("Hi, " + p.getName() + "!"); } sayHiTo(stu); remember: a Student is a Person stu (Student) & p (Person) & Hi, Fred "Fred" "A001234"

  49. Polymorphism Poly = many; morph = shape Person variable can refer to lots of different object types: Person, Student, UnderGrad, GradStudent, Faculty, Staff, so long as they extend Person directly or indirectly extends Person has all the Person methods so the Person variable can be used to call them it s really all about having the methods

  50. Having the Methods Any Person parameter refers to an object that has all the Person methods Any Student parameter refers to an object that has all the Student methods Do we need a Student or just a Person? look at the methods the parameter needs calls Student method needs Student parameter

Related


More Related Content