Overview of the lecture. Some key issues in programming Java programming. CMPT Data and Program Abstraction. Some of the key programming issues

Similar documents
Making New instances of Classes

Important when developing large programs. easier to write, understand, modify, and debug. each module understood individually

Data Abstraction: The Walls

Chapter 4.!Data Abstraction: The Walls! 2011 Pearson Addison-Wesley. All rights reserved 4-1

Chapter 5 Object-Oriented Programming

Object Oriented Programming. Java-Lecture 11 Polymorphism

Chapter 10 Classes Continued. Fundamentals of Java

CS Internet programming Unit- I Part - A 1 Define Java. 2. What is a Class? 3. What is an Object? 4. What is an Instance?

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Argument Passing All primitive data types (int etc.) are passed by value and all reference types (arrays, strings, objects) are used through refs.

Chapter 1: Programming Principles

CMSC 132: Object-Oriented Programming II

The design of an ADT should evolve naturally during the problem-solving process Questions to ask when designing an ADT

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe

Programming II (CS300)

Chapter 1: Principles of Programming and Software Engineering

Exception-Handling Overview

Class, Variable, Constructor, Object, Method Questions

CH. 2 OBJECT-ORIENTED PROGRAMMING

15CS45 : OBJECT ORIENTED CONCEPTS

CREATED BY: Muhammad Bilal Arslan Ahmad Shaad. JAVA Chapter No 5. Instructor: Muhammad Naveed

Inheritance and Polymorphism

Lecture Notes Chapter #9 Summery. Inheritance

COMP200 - Object Oriented Programming: Test One Duration - 60 minutes

Java Inheritance. Written by John Bell for CS 342, Spring Based on chapter 6 of Learning Java by Niemeyer & Leuck, and other sources.

Inheritance. Transitivity

OOPS Viva Questions. Object is termed as an instance of a class, and it has its own state, behavior and identity.

Programming II (CS300)

QUESTIONS FOR AVERAGE BLOOMERS

Full file at Chapter 2 - Inheritance and Exception Handling

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

EXCEPTION HANDLING. Summer 2018

CS-202 Introduction to Object Oriented Programming

Inheritance and object compatibility

Object Oriented Programming in Java. Jaanus Pöial, PhD Tallinn, Estonia

COP 3330 Final Exam Review

Object Oriented Issues in VDM++

PROGRAMMING LANGUAGE 2

Lecture Chapter 2 Software Development

Practice for Chapter 11

Compaq Interview Questions And Answers

What s Conformance? Conformance. Conformance and Class Invariants Question: Conformance and Overriding

Java Object Oriented Design. CSC207 Fall 2014

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner.

Logistics. Final Exam on Friday at 3pm in CHEM 102

CMSC 132: Object-Oriented Programming II

Program Correctness and Efficiency. Chapter 2

What is Inheritance?

CS 251 Intermediate Programming Inheritance

2.6 Error, exception and event handling

Critique this Code. Hint: It will crash badly! (Next slide please ) 2011 Fawzi Emad, Computer Science Department, UMCP

Chapter 4 Defining Classes I

Declarations and Access Control SCJP tips

CO Java SE 8: Fundamentals

Object Oriented Features. Inheritance. Inheritance. CS257 Computer Science I Kevin Sahr, PhD. Lecture 10: Inheritance

Lecture 2: Java & Javadoc

Chapter 11 Inheritance and Polymorphism. Motivations. Suppose you will define classes to model circles,

Data Structures and Algorithms Design Goals Implementation Goals Design Principles Design Techniques. Version 03.s 2-1

Inheritance. SOTE notebook. November 06, n Unidirectional association. Inheritance ("extends") Use relationship

I pledge by honor that I will not discuss this exam with anyone until my instructor reviews the exam in the class.

Lecture 36: Cloning. Last time: Today: 1. Object 2. Polymorphism and abstract methods 3. Upcasting / downcasting

Objective Questions. BCA Part III Paper XIX (Java Programming) page 1 of 5

Data Abstraction. Hwansoo Han

Inheritance & Polymorphism Recap. Inheritance & Polymorphism 1

24. Inheritance. Java. Fall 2009 Instructor: Dr. Masoud Yaghini

Programming Language Concepts Object-Oriented Programming. Janyl Jumadinova 28 February, 2017

COMP200 INHERITANCE. OOP using Java, from slides by Shayan Javed

Inheritance (Part 5) Odds and ends

C++ Important Questions with Answers

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS

CLASSES AND OBJECTS IN JAVA

Classes. Classes. Classes. Class Circle with methods. Class Circle with fields. Classes and Objects in Java. Introduce to classes and objects in Java.

Polymorphism. return a.doublevalue() + b.doublevalue();

IT101. Inheritance, Encapsulation, Polymorphism and Constructors

Chapter 10 Inheritance and Polymorphism. Dr. Hikmat Jaber

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University

22. Inheritance. Java. Summer 2008 Instructor: Dr. Masoud Yaghini

Conformance. Object-Oriented Programming Spring 2015

CS 11 java track: lecture 3

More on Objects in JAVA TM

What are the characteristics of Object Oriented programming language?

CISC-124. Passing Parameters. A Java method cannot change the value of any of the arguments passed to its parameters.

Inheritance -- Introduction

CS 61B Data Structures and Programming Methodology. July 7, 2008 David Sun

Inheritance, and Polymorphism.

1.00 Lecture 13. Inheritance

Object-Oriented Programming

Fundamentals of Object Oriented Programming

What does it mean by information hiding? What are the advantages of it? {5 Marks}

PESIT Bangalore South Campus

Today. Book-keeping. Inheritance. Subscribe to sipb-iap-java-students. Slides and code at Interfaces.

CS61B Lecture #12. Programming Contest: Coming up Saturday 5 October. See the contest announcement page, here.

CSEN401 Computer Programming Lab. Topics: Object Oriented Features: Abstraction and Polymorphism

Introduction to Object-Oriented Programming

ENCAPSULATION. private, public, scope and visibility rules. packages and package level access.

UNIT 3 ARRAYS, RECURSION, AND COMPLEXITY CHAPTER 11 CLASSES CONTINUED

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

CSE1720. General Info Continuation of Chapter 9 Read Chapter 10 for next week. Second level Third level Fourth level Fifth level

Exceptions. References. Exceptions. Exceptional Conditions. CSE 413, Autumn 2005 Programming Languages

HAS-A Relationship. If A uses B, then it is an aggregation, stating that B exists independently from A.

Transcription:

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