Understanding Java Inheritance and Interfaces with Polymorphism

interfaces n.w
1 / 67
Embed
Share

Explore Java inheritance concepts, from superclass to subclass, and delve into the implementation of interfaces, including Comparable and Comparator. Learn about Single Abstract Method interfaces and the Swing inheritance hierarchy. Discover the nuances of extending classes and the importance of method overriding. Gain insights into the Object class and essential methods for Java programming.

  • Java Programming
  • Inheritance
  • Polymorphism
  • Interfaces
  • Swing Hierarchy

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. Interfaces with Polymorphism and Lambda Expressions

  2. Outcomes 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

  3. Review of Inheritance One class a specialized version of another JLabel is a specialized JComponent JPanel is a specialized JComponent specialized version called subclass less specialized version called superclass Subclass gets all public superclass methods can inherit from classes that inherit from others inheritance hierarchy

  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. Review of Inheritance Use extends keyword public class Student extends Person Use super( ) in constructor public Student(String name) { super(name); // calls Person constructor Use @Override to change methods and super. to access inherited version of method @Override public String toString() { return super.toString() + " (" + A_NUM + ")"; }

  6. Single Inheritance Java allows only single inheritance can only extend one class public class StudentEmployee extends Student, Employee Because of diamond problem say Student & Employee both define toString Student name + A-number Employee name + SIN which version does StudentEmployee use? "Sam (A00000000)" or "Sam (000-000-000)"

  7. The Object Class Superclass to every Java class no extends keyword extends Object NOTE: int, double, boolean, char are NOT classes Important methods from Object: toString() translate to String equals(Object) check for same content each of those needs to be overridden to be useful

  8. Inheritance Consider add method in Swing defined in Container class expects to be given a Component JPanel and JFrame are both Containers JPanel JComponent Container JFrame Frame Window JComponent Container Both inherit that add method same method definition used in both classes

  9. and Polymorphism JLabel, JTextField, JButton are Components add method expects to be given a Component each can be given to the add method One method definition; six different calls add JLabel to JPanel add JTextField to JPanel add JButton to JPanel Works for any Container and Component so way more than just six different calls add JLabel to JFrame add JTextField to JFrame add JButton to JFrame

  10. What about setLayout? setLayout defined in Container class inherited by JFrame and JPanel (among others) expects to be given a LayoutManager Some LayoutManagers are: BorderLayout (items placed at edges or centre) GridLayout (items placed in a table) FlowLayout (items placed next to each other and wrapped as necessary)

  11. No LayoutManager Class! LayoutManagers do not inherit methods they need to know how to lay out a container but each does it in its own way LayoutManager operations: add a Component to the layout remove a component from the layout calculate the minimum size of the layout calculate the preferred size of the layout lay out the Components in the Container

  12. What, not How Each LayoutManager has its own way of doing the things it needs to do put it in a table, on a line, in a particular place Nothing in common no method definition works for all LMs exceptwhat needs to be done those same five operations need to be done but no restriction on how they get done

  13. Interfaces LayoutManager is an interface a list of methods to be implemented public interface LayoutManager { public void addLayoutComponent(String name, Component comp); public void removeLayoutComponent(Component comp); public Dimension minimumLayoutSize(Container parent); public Dimension preferredLayoutSize(Container parent); public void layoutContainer(Container parent); } no method bodies: no how; just what

  14. Implementing an Interface Each LM class implements that interface public class GridLayout implements LayoutManager { } public class BorderLayout implements LayoutManager { } public class FlowLayout implements LayoutManager { } says I know how to do those things! not allowed to lie about that! Each LM class defines those five methods but each has its own separate definition not inherited from anywhere

  15. Why Use Interfaces? We can say what needs doing without saying how it needs to be done e.g. Containers will need to be laid out different containers will want different layouts but there are these five things any layout needs to be able to do so we specify what those five things are and let the actual classes worry about how to do them

  16. Java Interfaces Just list the methods in the interface public interface Measurable { public double getArea(); public double getPerimeter(); } import java.awt.Color; public interface Colourable { public Color getColor(); public void setColour(Color c); } NOTE: methods with no body are called abstract methods.

  17. Implementing an Interface If you say you implement an interface public class Rectangle implements Measurable you must define all its methods @Override public double getArea() { return length * width; } @Override public double getPerimeter() { return 2 * (length + width); }

  18. Implementing an Interface If you say you implement an interface public class Circle implements Measurable you must define all its methods @Override public double getArea() { return Math.PI * Math.pow(radius, 2); } @Override public double getPerimeter() { return 2 * Math.PI * radius; } NOTE: totally different definitions than for Rectangle

  19. Using an Interface Tell method to expect a Measurable object can use any Measurable method for that object getArea or getPerimeter public static double roundness(Measurable m) { return 4 * Math.PI * m.getArea() / Math.pow(m.getPerimeter(), 2); cannot use any other methods! (*) we don t know what other methods it might have (*) actually, we can still call Object methods See MeasuringStuff.java

  20. Using an Interface roundness works for any Measurable object Circle c = new Circle(10.0); System.out.println("Roundness of c is " + roundness(c)); c has getArea and getPerimeter methods because Circles are Measurables so method works just fine similarly for Rectangles Rectangle r = new Rectangle(10.0, 20.0); System.out.println("Roundness of r is " + roundness(r)); Roundness of c is 1.0 Roundness of r is 0.6981317007977318

  21. Exercise Declare an interface named Playable that has the following methods: void play() void play(int numTimes) double playLength()

  22. Non-Interface Methods Class may have methods that are not part of the interface Rectangle: getHeight & getWidth Circle: getRadius & getCircumference Polymorphic parameters/variables cannot use those methods can only use interface methods

  23. The Circle Implementation public class Circle implements Measurable { private double radius; public Circle(double r) public double getRadius() public double getCircumference() public double getDiameter() @Override public double getArea() { return Math.PI * Math.pow(radius, 2); } @Override public double getPerimeter () } says it implements Measurable, then does has other methods, too but that s OK { radius = r; } { return radius; } { return 2 * Math.PI * radius; } { return 2 * radius; } { return getCircumference(); } See Circle.java

  24. The Rectangle Implementation public class Rectangle implements Measurable { private double length, width; public Rectangle(double l, double w) public double getLength() public double getWidth() @Override public double getArea() @Override public double getPerimeter () } says it implements Measurable, then does the implementations are different than for Circles { length = l; width = w; } { return length; } { return width; } { return length * width; } { return 2 * (length + width); } See Rectangle.java

  25. Whats OK? Methods you can ask for depend on the variable, not the object Circle c = new Circle(10); c.getPerimeter(); c.getArea(); c.getRadius(); c.getCircumference(); Rectangle r = new Rectangle(10, 20); r.getPerimeter(); r.getArea(); r.getHeight(); r.getWidth(); Measurable m = new Circle(10); m.getPerimeter(); m.getArea(); m.getRadius(); m.getCircumference();

  26. Compile-Time Method Checking Try to make sure program won t crash make it as safe as we can (no guarantees!) Asking a Rectangle for its radius would cause a crash Measurable could be a Rectangle Asking a Measurable for its radius could cause a crash

  27. Run-Time Method Selection Anything we ask a Measurable to do... ...will be part of the interface because our compile-time checking made sure The Measurable object knows how to do it because of compile-time checking of class Object uses its own version of the method known as late (or dynamic) binding In C++, early (static) binding chooses a version of the method at compile time.

  28. Measurable is a Data Type Can have a variable of type Measurable the parameter for roundness, for example Can assign it any Measurable object object of any class that implements Measurable Circles or Rectangles, for example Measurable m1 = new Rectangle(7, 200); Measurable m2 = new Circle(25); Mostly used to make polymorphic methods public double roundness(Measurable m) { }

  29. Variables & Types Measurable variable is polymorphic can hold a Circle or Rectangle object can assign from a different type variable Measurable m; Circle c = new Circle(10); Rectangle r = new Rectangle(10, 20); m = c; m = r; Compare storing an int variable into a double variable: int n = 5; double x = n;

  30. Variables & Types Cannot go the other way around Measurable m = new Circle(10); Rectangle r; Circle c; r = m; c = m; doesn t like either of those Compare storing a double variable into an int variable: double x = 5.0; int n = x;

  31. Type Casting Can tell Java you want to do it anyway! tell Java to treat the Measurable as a Circle Measurable m = new Circle(10); Circle c; c = (Circle) m; will crash if object is wrong type Rectangle r; r = (Rectangle) m; Crash Contrast casting a double variable into an int variable: double x = 5.5; int n = (int)x;

  32. Checking the Type Can ask if an object is a given type hey, m, are you are Circle? if (m instanceof Circle) { Circle c = (Circle) m; double radius = c.getRadius(); Still can t ask m to do non-Measurable stuff if (m instanceof Circle) { System.out.print(m.getRadius()); Note: all lower-case letters!

  33. Exercise Check a Measurable variable to see if it holds a Rectangle object. if it does, print out the Rectangle s length and width

  34. Interfaces and Inheritance A class may both extend and implement public class Both extends Parent implements Ability { extends has to come first no punctuation between the clauses Subclasses automatically implement public class SubBoth extends Both { SubBoth is a Both and Both implements Ability SubBoth implements Ability because Both does and SubBoth inherits all those methods

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

  36. Extending Interfaces Consider this interface: public interface Polygonal { // longer than it needs to be public double getArea(); public double getPerimeter(); public int getNumberOfSides(); } has all Measurable s methods, plus one more Can simplify the definition: public interface Polygonal extends Measurable { public int getNumberOfSides(); }

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

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

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

  40. Exercise What methods must these classes define? 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 F implements IC {...} public class G implements ID {...} public class H implements IA, IB {...} public class J implements IE {...} public class K extends F implements IA { }

  41. 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 method headers abstract methods have no body classes implement interfaces define the abstract methods for that interface may inherit definitions from super-class

  42. Java Uses Lots of Interfaces javax.swing defines 25 interfaces plus many more in sub-packages java.awt defines 17 interfaces plus many more in subpackages java.lang defines 9 interfaces these are the most generally useful interfaces one used, for example, in sorting arrays

  43. Interfaces and Sorting Arrays.sort sorts arrays of some types Java must know how to sort them knows how to sort int, double, String, doesn t know how to sort user-defined classes Tell Java how to sort user-defined classes Arrays.sort expects an array of Comparables objects that can be compared to each other implement the Comparable< > interface Comparable< > I can compare myself to

  44. Sorting Arrays Sort put into order usually smallest to largest [5, 1, 7, 3, 9] [1, 3, 5, 7, 9] Sorting by pair-wise comparisons compare two elements and maybe swap them [5, 1, ] 5 and 1 are out of order, so swap [ , 5, 7, ] 5 and 7 are OK, so no swap Keep going until no swaps left to make There are literally thousands pairs to compare. You will learn some of them in Data Structures. thousands of different ways of choosing which

  45. The Comparable<> Interface Have to fill in the < > what kind of thing it can be sorted with almost always itself public class Student implements Comparable<Student> public class Circle implements Comparable<Circle> Has exactly one abstract method @Override public int compareTo(Student other) how does this Student compare to other Student should this Student be before or after the other Student for Circle: public int compareTo(Circle other)

  46. The compareTo Method Based on sorting numbers and subtraction: a < b a b < 0 a comes before b a > b a b > 0 a comes after b a == b a b == 0 doesn t matter (equal) compareTo returns an int value a.compareTo(b) < 0 a comes before b a.compareTo(b) > 0 a comes after b a.compareTo(b) == 0 doesn t matter (equal) For integer numbers, can just return a b because a < b same as a b < 0.

  47. Sorting Students Let s sort Students by name name is a String String has a compareTo method so just return whatever it returns public int compareTo(Student other) { return this.name.compareTo(other.name); } if you want to compare Students, compare their names. See byName/Student.java

  48. Sorting Students Add Students to list; sort list; print list Student[] ss = new new Student[]{ new Student("Jake"), new Student("Angie"), new Student("Geety")}; Arrays.sort(ss); System.out.println(Arrays.toString(ss)); [Angie (A00000002), Geety (A00000003), Jake (A00000001)] See byName/SortStudents.java

  49. Sorting by Grade Sorting by numbers uses subtraction smallest to largest: this.number other.number largest to smallest: other.number this.number but result must be an int! public int compareTo(Student other) { return other.getAverage() this.getAverage(); } sorts Students from highest to lowest grade reverse one and other to sort lowest to highest See byGrade/Student.java and byGrade/SortStudents.java

  50. Sorting by Double Values Need to change double to int (int) no good changes 0.5 to 0 instead of 1 Use Math.signum to get sign of result then change to int public int compareTo(Line other) { double result = this.length other.length; double sign = Math.signum(result); // -1.0, 0.0, or +1.0 return (int)sign; } sorts from shortest to longest See Line.java and SortLines.java

More Related Content