Understanding Java Inheritance and Polymorphism

inheritance n.w
1 / 42
Embed
Share

"Explore the concepts of inheritance, polymorphism, and Swing hierarchy in Java programming. Learn how to declare and use inheritance effectively, differentiate between 'is' and 'has' relationships, and inherit methods in Java classes."

  • Java Programming
  • Inheritance
  • Polymorphism
  • Swing Hierarchy
  • Object-Oriented Programming

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

  2. Overview Inheritance & polymorphism inheriting method definitions overriding method definitions constructors in subclasses preventing overriding the equals method

  3. 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 GUIs and in Java in general

  4. Swing Inheritance Hierarchy JComponent is a subclass of Container Component Container JComponent is the superclass of JLabel Window JComponent JLabel Arrows point from subclass to superclass Frame JPanel JTextComponent AbstractButton JTextField JButton JFrame JTextArea This is, of course, only part of the Swing inheritance hierarchy JPasswordField

  5. Is vs. Has Is is not the same as Has JTextField is a Component JTextField doesn t have a Component a JPanel can have a JTextField (inside it) a JPanel is not a JTextField Compare: you are a person; you do not have a person you have a kidney; you are not a kidney

  6. Inheritance and Polymorphism If a method asks for a Component object public void add(Component c) { } any kind of Component object will do JTextField num1Field = new JTextField(); add(num1Field); Works with variable data types, too Component c = new JTextField(); add(c);

  7. Declaring Inheritance Need to tell Java about inheritance my class inherits from this other class e.g. JLabel inherits from JComponent Use the extends keyword public class JLabel extends JComponent { says that JLabel is a JComponent public class AdderDialog extends JFrame { says AdderDialog is a JFrame

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

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

  10. 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();

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

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

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

  14. Objects and Variables Each variable has a data type the kind of object it s allowed to refer to Each object has a data type the precise kind of thing it is it s also any kind of thing its data type inherits Java looks at the variable s data type to decide if a method call makes sense but if the call does make sense, Java uses the object s method definition for the call

  15. Variable vs. Object 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()); } } Parent objects don t have sayValue method. So Java won t let Parent variables call it. Parent p = new Child(); p.setValue("Fred"); p.sayValue();

  16. Variable vs. Object 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() { Sopln( My value is + this.getValue()); } @Override public String getValue() { return super.getValue().replace('r', 'w'); } } The variable is type Parent, and Parent objects have getValue method, so call is OK. But object is type Child, so uses Child s version of getValue. Parent p = new Child(); p.setValue("Fred"); Sopln(p.getValue()); Fwed

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

  18. Inheritance Hierarchies Java uses inheritance a lot for example, JTextField: javafx.scene.control Class TextField java.lang.Object java.awt.Component java.awt.Container javax.swing.JComponent javax.swing.text.JTextComponent javax.swing.JTextField TextField has 29 of its own methods inherits 416 others

  19. Constructors in Subclasses Recall purpose of constructor: 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 object has a value field need to set its value; but how?

  20. Constructors in Subclasses Subclass cannot just set instance variable: public class Child extends Parent { public Child(String requestedValue) { value = requestedValue; } } value is private to Parent Could use a setter (if Parent has one) public Child(String requestedValue) { setValue(requestedValue); } gets a warning: Overridable call in constructor subclass could override setValue and mess up your constructor!

  21. Preventing Inheritance Can tell Java no over-riding this method public final void setValue(String v) { } final method = method definition can t change method needsto work the way it s defined here prevents subclasses from restricting value Can also tell Java no subclasses public finalclass Scanner { } final class = class can t be sub-typed yes, java.util.Scanner is final; so is String

  22. Calling Constructors Recall overloading constructors choose one constructor to be the primary it sets every instance variable have other constructors call it, using this( ) public Parent(String reqValue) { value = reqValue; } public Parent() { this("No value given"); } calls Parent(String reqValue) value set to No value given Child needs to call Parent s constructor

  23. Calling Parents Constructor Can t just call the constructor public Child(String reqValue) { Parent(reqValue); } cannot find symbol: method Parent(String) The super keyword already seen super for calling Parent s method also used for constructor public Child(String reqValue) { super(reqValue); } calls Parent(String reqValue) Parent s constructor sets value to reqValue

  24. 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!

  25. Notes on Constructors Every class has a constructor even if you don t give it one If you don t give a class a constructor it gets a constructor like this one: public MyClassName() { } named after class (as required) does nothing Note: only if you give it NO constructors

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

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

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

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

  30. 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 ; } }

  31. 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; } }

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

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

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

  35. 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)

  36. 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)

  37. 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)

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

  39. 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) { }

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

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

  42. Questions Next week: Review on Tuesday Test on Thursday during lecture hours on Brightspace open book After break more on polymorphism

More Related Content