1 / 68

Lecture 3

Lecture 3. Topics. Review the contents in last class. More examples for class and inheritance. Equality Exception. class variable. class Circle { public static final double PI = 3.14159; public double x, y, r; } public class example{ public static void main(String[] args){

clyde
Download Presentation

Lecture 3

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Lecture 3

  2. Topics • Review the contents in last class. • More examples for class and inheritance. • Equality • Exception

  3. class variable • class Circle { • public static final double PI = 3.14159; • public double x, y, r; • } • public class example{ • public static void main(String[] args){ • Circle.PI = 4; • } • } • Is this correct?

  4. class variable • class Circle { • public static final double PI = 3.14159; • public double x, y, r; • } • public class example{ • public static void main(String[] args){ • Circle.PI = 4; //Error • } • } • The final keyword means that this variable can never be changed.

  5. class method public class Circle { public double x, y, r; // an class method. Returns the bigger of two circles. public static Circle bigger(Circle c){ if(c.r > r) return c; else return this; } //other methods omitted here. } • Is this correct?

  6. class method public class Circle { public double x, y, r; // an class method. Returns the bigger of two circles. public static Circle bigger(Circle c){ if(c.r > r) //Error return c; else return this; //Error } } • static methods may not manipulate any instance variables!

  7. Shape Classes • We have a class called Shape • assume all shapes have x and y coordinates • override Object's version of toString • Two subclasses of Shape • Rectangle • Circle

  8. A Shape class public class Shape { private double dMyX, dMyY; public Shape() { this(0,0);} public Shape (double x, double y) { dMyX = x; dMyY = y; } public String toString() { return "x: " + dMyX + " y: " + dMyY; } public double getArea() { return 0; } }

  9. A Rectangle Class public class Rect extends Shape{ private double dMyWidth, dMyHeight; public Rect(double width, double height) { dMyWidth = width; dMyHeight = height; } public String toString() { return " width " + dMyWidth + " height " + dMyHeight; } public double getArea() { return dMyWidth * dMyHeight; } public void changeWidth(double width){ dMyWidth = width; } }

  10. A Circle Class class Circle extends Shape { private double radius; private static final double PI = 3.14159; public Circle(double rad){ radius = rad; } public double getArea() { return PI * radius * radius; } public String toString() { return " radius " + radius; } }

  11. Object Variables Rect r = new Rect(10, 20); Shape s = r; System.out.println("Area is " + s.getArea()); • Assume class Rect is a subclass of class Shape, and it overrides the method getArea(). • Does this work?

  12. Object Variables Rect r = new Rect(10, 20); Shape s = r; System.out.println("Area is " + s.getArea()); • The above code works if Rect extends Shape • An object variable may point to an object of its base type or a descendant in the inheritance chain • The is-a relationship is met. A Rect is-a shape so s may point to it • This is a form of polymorphism.

  13. More Polymorphism Circle c = new Circle(5);Rect r = new Rect(5, 3);Shape s = null;if( Math.random(100) % 2 == 0 ) s = c;else s = r;System.out.println( "Shape is " + s.toString() ); • Assuming Circle and Rect are subclasses of Shape, and have both overridden toString(), which version gets called?

  14. More Polymorphism Circle c = new Circle(5);Rect r = new Rect(5, 3);Shape s = null;if( Math.random(100) % 2 == 0 ) s = c;else s = r;System.out.println( "Shape is " + s.toString() ); • code works because s is polymorphic • method call determined at run time by dynamic binding

  15. Type Compatibility Rect r = new Rect(5, 10);Shape s = r;s.changeWidth(20); • Assume class Rect is a subclass of class Shape, and it has a new method changeWidth(double width), which its super class does not have. • Does this work?

  16. Type Compatibility Rect r = new Rect(5, 10);Shape s = r;s.changeWidth(20); // syntax error • polymorphism allows s to point at a Rect object but there are limitations • The above code does not work • How can you modify it a little to make it work without changing the classes definitions?

  17. Type Compatibility Rect r = new Rect(5, 10);Shape s = r;s.changeWidth(20); // syntax error • polymorphism allows s to point at a Rect object but there are limitations • The above code does not work • Statically s is declared to be a shape • no changeWidth method in Shape class • must cast s to a rectangle; Rect r = new Rect(5, 10);Shape s = r;((Rect)s).changeWidth(20); //Okay

  18. Problems with Casting Rect r = new Rect(5, 10);Circle c = new Circle(5);Shape s = c;((Rect)s).changeWidth(4); • Does this work?

  19. Problems with Casting • The following code compiles but an exception is thrown at runtime • Casting must be done carefully and correctly • If unsure of what type object will be then use the instanceofoperator Rect r = new Rect(5, 10);Circle c = new Circle(5);Shape s = c;((Rect)s).changeWidth(4);

  20. instanceof Rect r = new Rect(5, 10);Circle c = new Circle(5);Shape s = c; if(s instanceof Rect) ((Rect)s).changeWidth(4); • syntax: expression instanceof ClassName

  21. Casting • It is always possible to convert a subclass to a superclass. For this reason, explicit casting can be omitted. For example, • Circle c1 = new Circle(5); • Shape s = c1; is equivalent to • Shape s = (Shape)c1; • Explicit casting must be used when casting an object from a superclass to a subclass. This type of casting may not always succeed. • Circle c2 = (Circle) s;

  22. The abstract Modifier • The abstract class • Cannot be instantiated • Should be extended and implemented in subclasses • The abstract method • Method signature without implementation

  23. Abstract Classes GeometricObject Circle Cylinder Rectangle

  24. Note An abstract method cannot be contained in a nonabstract class. If a subclass of an abstract superclass does not implement all the abstract methods, the subclass must be declared abstract. In other words, in a nonabstract subclass extended from an abstract class, all the abstract methods must be implemented, even if they are not used in the subclass.

  25. Note An abstract class cannot be instantiated using the new operator, but you can still define its constructors, which are invoked in the constructors of its subclasses. For instance, the constructors of GeometricObject are invoked in the Circle class and the Rectangle class.

  26. NOTE A class that contains abstract methods must be abstract. However, it is possible to declare an abstract class that contains no abstract methods. In this case, you cannot create instances of the class using the new operator. This class is used as a base class for defining a new subclass.

  27. NOTE A subclass can be abstract even if its superclass is concrete. For example, the Object class is concrete, but its subclasses, such as GeometricObject, may be abstract.

  28. NOTE A subclass can override a method from its superclass to declare it abstract. This is rare, but useful when the implementation of the method in the superclass becomes invalid in the subclass. In this case, the subclass must be declared abstract.

  29. NOTE You cannot create an instance from an abstract class using the new operator, but an abstract class can be used as a data type. Therefore, the following statement, which creates an array whose elements are of GeometricObject type, is correct. GeometricObject[] geo = new GeometricObject[10];

  30. Polymorphism Consider the code in the next page: What is the output?

  31. public class Test { public static void main(String[] args) { m(new A()); //?? m(new B()); //?? m(new C()); //?? m(new Object()); //?? } public static void m(Object o) { System.out.println(o.toString()); } } class A extends B {} class B extends C { public String toString() { return "B"; } } class C extends Object { public String toString() { return "C"; } }

  32. public class Test { public static void main(String[] args) { m(new A()); // B m(new B()); //B m(new C()); //C m(new Object()); //java.lang.Object@192d342 } public static void m(Object o) { System.out.println(o.toString()); } } class A extends B {} class B extends C { public String toString() { return "B"; } } class C extends Object { public String toString() { return "C"; } }

  33. Polymorphism Method m (Line 9) takes a parameter of the Object type. You can invoke m with any objects (e.g. new A(), new B(), new C(), and new Object())in Lines (3-6). An object of a subclass can be used by any code designed to work with an object of its superclass. This feature is known as polymorphism (from a Greek word meaning “many forms”).

  34. Dynamic Binding When the method m is executed, the argument x’s toString method is invoked. x may be an instance of A, B, C, or Object. Classes A, B, C, and Object have their own implementation of the toString method. Which implementation is used will be determined dynamically by the Java Virtual Machine at runtime. This capability is known as dynamic binding.

  35. Dynamic Binding, cont. Dynamic binding works as follows: Suppose an object o is an instance of classes C1, C2, ..., Cn-1, and Cn, where C1 is a subclass of C2, C2 is a subclass of C3, ..., and Cn-1 is a subclass of Cn. That is, Cn is the most general class, and C1 is the most specific class. In Java, Cn is the Object class. If o invokes a method p, the JVM searches the implementation for the method p in C1, C2, ..., Cn-1 and Cn, in this order, until it is found. Once an implementation is found, the search stops and the first-found implementation is invoked.

  36. toString() • The toString() method returns a string representation of the object. • The default implementation returns a string consisting of a class name of which the object is an instance, the at sign (@), and a number representing this object.

  37. Generic Programming Polymorphism allows methods to be used generically for a wide range of object arguments. This is known as generic programming. If a method’s parameter type is a superclass (e.g.,GeometricObject), you may pass an object to this method of any of the parameter’s subclasses (e.g., Circle or Rectangle). When an object (e.g., a Circle object or a Rectangleobject) is used in the method, the particular implementation of the method of the object that is invoked (e.g., findArea) is determined dynamically.

  38. Example: Testing Polymorphism • File in TestPolymorphism.htm • Objective: This example creates two geometric objects: a circle, and a rectangle, invokes the equalArea method to check if the two objects have equal area, and invokes the displayGeometricObject method to display the objects.

  39. Note • Matching a method signature and binding a method implementation are two issues. • The compiler finds a matching method according to parameter type, number of parameters, and order of the parameters at compilation time. • A method may be implemented in several subclasses. The JVM dynamically binds the implementation of the method at runtime.

  40. Example: Casting Objects Code in TestCasting.htm This example creates two geometric objects: a circle, and a cylinder, invokes the displayGeometricObject method to display the objects. The displayGeometricObject displays the area and perimeter if the object is a circle, and displays area and volume if the object is a cylinder.

  41. Interfaces • What Is an Interface? • Creating an Interface • Implementing an Interface

  42. Creating an Interface modifier interface InterfaceName { constants declarations; methods signatures; }

  43. Example of Creating an Interface // This interface is defined in // java.lang package public interface Comparable { public int compareTo(Object o); }

  44. Generic max Method public class Max { // Return the maximum between two //objects public static Comparable max (Comparable o1, Comparable o2) { if (o1.compareTo(o2) > 0) return o1; else return o2; } }

  45. Example Using Interfaces • Code in TestInterface.htm • Objective: Use the max method to find the maximum circle between two circles and a maximum cylinder between two cylinders.

  46. Interface example, cont.

  47. Interfaces vs. Abstract Classes In an interface, the data must be constants; an abstract class can have all types of data. Each method in an interface has only a signature without implementation; an abstract class can have concrete methods. An abstract class must contain at least one abstract method or inherit from another abstract method.

  48. Interfaces vs. Abstract Classes, cont. Since all the methods defined in an interface are abstract methods, Java does not require you to put the abstract modifier in the methods in an interface, but you must put the abstract modifier before an abstract method in an abstract class.

  49. Inner Classes Inner class: A class is a member of another class. Advantages: In some applications, you can use an inner class to make programs simple. • An inner class can reference the data and methods defined in the outer class in which it nests, so you do not need to pass the reference of the outer class to the constructor of the inner class.

  50. // ShowInnerClass.java: Demonstrate using inner classes public class ShowInnerClass { private int data; // A method in the outer class public void m() { // Do something InnerClass instance = new InnerClass(); } // An inner class class InnerClass { public void mi() { // A method in the inner class // Directly reference data and method defined in its outer class data++; m(); } } }

More Related