Overview of the lecture CMPT 201 - Data and Program Abstraction Instructor: Snezana Mitrovic-Minic Some key issues in programming Java programming equality of objects inheritance Is-a and has-a relationship Java interface dynamic binding and abstract classes Java exceptions 2 Some of the key programming issues Some key issues in programming Modularity Modifiability Easy of use Fail-safe programming Style Debugging 3 4 Modularity - How to determine modules? What helps: abstraction and information hiding procedural abstraction: separate the purpose of a method from its implementation data abstraction: Abstract Data Types (ADT) information hiding (all modules and ADTs should hide something) object-oriented design encapsulation - hides inner details inheritance - classes can inherit properties from other classes polymorphism - outcome of an operation depends on the objects on which the operation acts - determined at the execution time top-down design (emphasis on algorithm) address the problem at successively lower levels of details Modularity helps: modularity makes programming easier modularity permits team work modularity makes debugging easier modularity makes reading of a program easier modularity makes modifications easier modularity eliminates redundant code 5 6 1
Modifiability and Easy of use Modifiability - keep programmers in mind modifiability = easy to modify a program what helps: modularity, naming constants,... Fail-safe programming Program has to perform reasonably no matter how anyone uses it. Try to anticipate the ways people could misuse the program - and guard against it. Easy of use - keep users in mind friendly and good user interface prompt user for input, and echo the input label the output and make it easy to read,... How: check for errors in user input check for errors in logic method should enforce their preconditions and check the values of its arguments,... 7 8 Programming Style extensive use of methods use of private data fields error handling (in case of error, method should return a value or throw an exception) readability documentation an initial comment of the program (statement of purpose, author and date, description of the program s input and output, description of how to use program, assumptions (such as the type of data expected), statement of exceptions - what it could go wrong, brief description of major classes) initial comments in each class: state purpose and describe data contained initial comments for each method: state its purpose, preconditions, postconditions, and methods called comments in the body of each method: explain important features or subtle logic 9 Debugging Tracking down errors systematically. A programming environment with a debugger: stepping through a program, setting breakpoints, using watches Without a debugger: set your watches and temporary 6\V WHP RXWS ULQWOQ statements Use these debugging facilities - at strategic locations in a program place them at entry and departure points of a method check key variables at the beginning and ends of loops check variables that appear in LIÃexpression, beforeãliã statement place them at some other key points in a method use dump methods (methods for displaying complex data structures),... 10 Java Inheritance and more 11 public class Sphere { private double theradius; public Sphere() { setradius(1.0); public Sphere(double initialradius) { setradius(initialradius); return ((rhs instanceof Sphere) && (theradius == ((Sphere)rhs).theRadius)); public void setradius(double newradius) { if (newradius >= 0.0) { theradius = newradius; public double radius() { public double area() { public double volume() { public void displaystatistics() { //end Sphere 12 2
public class Sphere { private double theradius; public Sphere() { setradius(1.0); public Sphere(double initialradius) { setradius(initialradius); return ((rhs instanceof Sphere) && (theradius == ((Sphere)rhs).theRadius)); public void setradius(double newradius) { if (newradius >= 0.0) { theradius = newradius; public double radius() { public double area() { public double volume() { public void displaystatistics() { //end Sphere 13 public ColoredSphere(Color c, double initialradius) {... (theradius == ((Sphere)rhs).theRadius) && (color == ((Sphere)rhs).color)); public Color getcolor() {... 14 public ColoredSphere(Color c, double initialradius) {... (theradius == ((Sphere)rhs).theRadius) && (color == ((Sphere)rhs).color)); public Color getcolor() {... public ColoredSphere(Color c, double initialradius) {... (theradius == ((Sphere)rhs).theRadius) && (color == ((Sphere)rhs).color)); public Color getcolor() {... 15 16 Inheritance Sphere is a base class or superclass. ColoredSphere is a derived class or subclass of Sphere. Declaring a class without extends clause, implicitly extends the class Object. public ColoredSphere(Color c, double initialradius) {... (theradius == ((ColoredSphere)rhs).theRadius) && (color == ((ColoredSphere)rhs).color)); public Color getcolor() {... 17 18 Subclass: inherits the contents of the superclass public members of superclass are available in subclass constructor of a subclass has to invoke super() to call the constructor of the superclass. (super() has to precede all other statements in the constructor). methods of superclass can be overridden. Method in subclass overrides a method in superclass if the two methods have the same declaration 3
Is-a Relationship Inheritance should be used only when an is-a relationship exists between the superclass and the subclass. ColoredSphere is a Sphere An instance of a subclass can be used anywhere where an instance of the superclass can be used. Not the other way around. Actual argument in a call to a method can be a subclass of the corresponding formal parameter. For example: All the classes are derived from the Object class. Therefore, type Object can be used as the type of a formal parameter, and object of any class can be used as the actual argument. 19 public class Ball extends Sphere { private String thename; // the ball s name public Ball() { setname("unknown"); public Ball(double initialradius, String initialname) { super(initialradius); setname(initialname); return ((rhs instanceof Ball) && (radius() == ((Ball)rhs).radius()) && (thename.compareto(((ball)rhs).thename)==0) ); public void displaystatistics() { System.out.print("\nStatistics for a "+ name()); super.displaystatistics(); 20 Is-a Relationship (cont) Has-a Relationships Program uses Sphere and Ball. Program contains method: public void displayradius (Sphere thing) { System.out.println("Radius is " + thing.radius() +"."; A ball-point pen has a ball as its point. Use inheritance? Valid calls to the method are: Sphere mysphere = new Sphere(); ColoredSphere myball = new Ball(); displayradius(mysphere); displayradius(myball); 21 22 Has-a Relationships A ball-point pen has a ball as its point. Has-a Relationships A ball-point pen has a ball as its point. Use inheritance? Use inheritance? Å because a pen is not a ball. Use data field point whose type is Ball. public class Pen { private Ball point;... Instance Pen has, or contains an instance of a Ball. Has-a relationship is sometimes called containment. 23 24 4
Object equality Java package groups related classes together. sphere1.equals(sphere2) compares two references. You can customize HTXDOV for a class. If drawingpackage is to contain class Pallete: package drawingpackage; public class Pallete { To use classes from drawingpackage import drawingpackage.*; or to use one class from drawingpackage import drawingpackage.pallete; 25 26 Java Access Modifiers control the visibility of the members of a class. public members can be used anywhere private members can be used by methods of the class protected members can be used only by methods of the class, methods of other classes in the same package, and methods of the subclasses Members declared without an access modifier are available to methods of the class and methods of other classes in the same package Java Interface 27 28 Java Interface A Java interface specifies the common behavior of a set of classes. public interface AnimateInterface { public final double CONST = 1.1111; // a constant public void move(int x, int y); public void paint(); public class AnimateBall extends Ball implements AnimateInterface { Java Interface (cont) Example: Dog is an animal class Dog is a subclass of class Animal Dog is a Pet. But because Dog already has a superclass (Animal), the Dog cannot have another superclass. Therefore, in order to be sure that Dog implements methods needed for a Pet, we can create Pet interface, and... public interface PetInterface { public takewalk(); public class Dog extends Animal implements PetInterface { 29 30 5
Dynamic binding Ball myball = new Ball(1.25, basketball ); Sphere mysphere = myball; mysphere.displaystatistics(); Dynamic Binding mysphere references to instance of Ball class the Ball version of displaystatistics is executed. It is decided at execution time - late binding or dynamic binding. Also, displaystatistics of class Ball overrides displaystatistics of class Sphere. 31 32 Overriding and Overloading Two methods with the same name and the same set of parameters - one method overrides the other. Two methods with the same name and the different set of parameters - second method overloads the first. Frequently, you overload constructors. Abstract Classes 33 34 Abstract class An abstract class has no instances and is used only as the basis of other classes. An abstract class - provide implementations of few methods (access to private data fields). A class that contains at least one abstract method must be declared as an abstract class. A subclass of an abstract class must be declared abstract if it does not provide implementations for all abstract methods of superclass. public abstract class EquidistantShape { private double theradius; // it can be protected instead of private public void setradius(double newradius) { if (newradius >= 0.0) { theradius = newradius; public double radius() { return theradius; public abstract void displaystatistics(); 35 36 6
public class SphereP351 extends EquidistantShape { public SphereP351() { setradius(1.0); public SphereP351(double initialradius) { setradius(initialradius); // Implementation of abstract method public void displaystatistics() { System.out.println("\nRadius = " + radius() + "\ndiameter = " + diameter() + "\ncircumference = " + circumference() + "\narea = " + area() + "\nvolume = " + volume()); // Remaining methods for class appear here 37 38 Exception is a mechanism for handling an error during execution. A method indicates that an error has occurred by throwing an exception. The exception returns to the point where the method was called, where you catch the exception and deal with the error condition. Exception is a mechanism for handling an error during execution. A method indicates that an error has occurred by throwing an exception. The exception returns to the point where the method was called, where you catch the exception and deal with the error condition. Java has two types of exceptions: checked exceptions - instances of java.lang.exception or its subclasses. They must be handled locally or explicitly thrown from the method. They are used for serious problems (FileNotFoundException, ) runtime exceptions - instances of RuntimeException class (a subclass of Exception) or of its subclasses. They are used when error is not considered as serious. These types of exceptions can be often handled by fail-safe programming. 39 40 Throwing exception: A method whose code can throw an exception: throw new exceptionclass(stringargument); Catching exception: try { statement(s); catch (exceptionclass identifier) { statement(s); public void mymethod() throws MyException { // some code throw new MyException ( May exception raised: reason ) 41 42 7