Ch. 2 Object-Oriented Programming

Slides:



Advertisements
Similar presentations
Data Structures Lecture 2 Fang Yu Department of Management Information Systems National Chengchi University Fall 2011.
Advertisements

Written by: Dr. JJ Shepherd
Inheritance Java permits you to use your user defined classes to create programs using inheritance.
Road Map Introduction to object oriented programming. Classes
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
© 2006 Pearson Addison-Wesley. All rights reserved4-1 Chapter 4 Data Abstraction: The Walls.
Object-Oriented Design. Method for designing computer programs Consider “objects” interacting in the program –Example: a zoo.
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
© 2006 Pearson Addison-Wesley. All rights reserved4-1 Chapter 4 Data Abstraction: The Walls.
Chapter 10 Classes Continued
OOP in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Programming Languages and Paradigms Object-Oriented Programming.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
CSM-Java Programming-I Spring,2005 Objects and Classes Overview Lesson - 1.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
CMSC 202 Exceptions. Aug 7, Error Handling In the ideal world, all errors would occur when your code is compiled. That won’t happen. Errors which.
Recap (önemli noktaları yinelemek) from last week Paradigm Kay’s Description Intro to Objects Messages / Interconnections Information Hiding Classes Inheritance.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Chapter 7 Objects and Classes 1 Fall 2012 CS2302: Programming Principles.
Object-Oriented Design CSC 212. Announcements This course is speeding up and we are starting new material. Please see me if you feel this is going too.
Data Structures Using Java1 Chapter 2 Inheritance and Exception Handling.
Object Oriented Programming
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 9 Java Fundamentals Objects/ClassesMethods Mon.
Object-Oriented Programming © 2013 Goodrich, Tamassia, Goldwasser1Object-Oriented Programming.
Introduction to Object-Oriented Programming Lesson 2.
Classes, Interfaces and Packages
Object orientation and Packaging in Java Object Orientation and Packaging Introduction: After completing this chapter, you will be able to identify.
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
Author: DoanNX Time: 45’.  OOP concepts  OOP in Java.
POLYMORPHISM Chapter 6. Chapter Polymorphism  Polymorphism concept  Abstract classes and methods  Method overriding  Concrete sub classes and.
 Description of Inheritance  Base Class Object  Subclass, Subtype, and Substitutability  Forms of Inheritance  Modifiers and Inheritance  The Benefits.
COP INTERMEDIATE JAVA Inheritance, Polymorphism, Interfaces.
COMPUTER SCIENCE & TECHNOLOGY DEGREE PROGRAMME FACULTY OF SCIENCE & TECHNOLOGY UNIVERSITY OF UVA WELLASSA ‏ Properties of Object Oriented Programming.
CSCE , SPRING 2016 INSTRUCTOR: DR. NANCY M. AMATO 1.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
Data Structures and Algorithms in JAVA Chapter 2.
CH 1-4 : INTRODUCTION ACKNOWLEDGEMENT: THE SLIDES ARE PREPARED FROM SLIDES PROVIDED WITH DATA STRUCTURES AND ALGORITHMS IN C++, GOODRICH, TAMASSIA AND.
Computer Programming II Lecture 5. Introduction to Object Oriented Programming (OOP) - There are two common programming methods : procedural programming.
Object-oriented programming (OOP) is a programming paradigm using "objects" – data structures consisting of data fields and methods together with their.
Copyright © 2012 Pearson Education, Inc. Chapter 4 Writing Classes : Review Java Software Solutions Foundations of Program Design Seventh Edition John.
The Object-Oriented Thought Process Chapter 03
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
Modern Programming Tools And Techniques-I
Data Abstraction: The Walls
Object-Oriented Design
Ch. 2 Object-Oriented Programming
Object-Oriented Programming
Inheritance and Polymorphism
Java Primer 1: Types, Classes and Operators
Lecture 2 of Computer Science II
Chapter 4: Writing Classes
Object-Oriented Programming
Subroutines Idea: useful code can be saved and re-used, with different data values Example: Our function to find the largest element of an array might.
Object-Oriented Programming
Python Primer 2: Functions and Control Flow
Java Programming Language
Week 6 Object-Oriented Programming (2): Polymorphism
Outline Writing Classes Copyright © 2012 Pearson Education, Inc.
Java – Inheritance.
COP 3330 Object-oriented Programming in C++
Object-Oriented Programming
CS2013 Lecture 7 John Hurley Cal State LA.
Final and Abstract Classes
Oriented Design and Abstract Data Type
CMSC 202 Exceptions.
Exception Handling.
Abstract Data Types Abstraction is to distill a system to its most fundamental parts. Applying the abstraction paradigm to the design of data structures.
Presentation transcript:

Ch. 2 Object-Oriented Programming 6/12/2018 Ch. 2 Object-Oriented Programming Acknowledgement: These slides are adapted from slides provided with Data Structures and Algorithms in Java, Goodrich, Tamassia and Goldwasser (Wiley 2016)

Crash course in object-oriented programming

Object-Oriented Design Principles Object Oriented Programming – paradigm for programming involving modularizing code into self contained objects that are a concise and consistent view of a “thing” without exposing unnecessary detail like the inner workings of the object Composition/Abstraction – What makes up an object? The model Encapsulation – Hiding implementation details, only exposing the “public interface” Inheritance – Types and subtypes, it’s a modeling decision Polymorphism – Provision of a single interface to entities of different types

Goals Robustness Adaptability Reusability We want software to be capable of handling unexpected inputs that are not explicitly defined for its application. Adaptability Software needs to be able to evolve over time in response to changing conditions in its environment. Reusability The same code should be usable as a component of different systems in various applications.

Object-Oriented Software Design Responsibilities Divide the work into different actors, each with a different responsibility. Independence Define the work for each class to be as independent from other classes as possible. Behaviors Define the behaviors for each class carefully and precisely, so that the consequences of each action performed by a class will be well understood by other classes that interact with it.

Terminology “object” is a little ambiguous Object type or class – specifies instance variables, also known as data members, that the object contains, as well as the methods, also known as member functions, that the object can execute Object instance, i.e., variable of that object type

Class Definitions A class serves as the primary means for abstraction in object-oriented programming. In Java, every variable is either a primitive type or is a reference to an instance of some class A class provides a set of behaviors in the form of member functions (also known as methods), with implementations that belong to all its instances. A class also serves as a blueprint for its instances, effectively determining the way that state information for each instance is represented in the form of attributes (also known as fields, instance variables, or data members).

Using a class (Quick and dirty refresher) Initialize a variable of an object with the keyword new followed by a call to a constructor of the object: String s = new String(“Hello”); Use a method of the class to execute a computation: int l = s.length();

Class template (Quick and dirty refresher) public class ClassName { /* All instance variables declared private*/ private int i = 0; /* Any public static final variables – these model constants */ /* All constructors – constructors initialize all member data, and must be named the same as the class */ public ClassName() {} /* All accessor (getters) and simple modifiers (setters) needed for the object */ public int getI() {return i;} public int setI(int i) {this.i = i;} /* All other public methods */ /* Any and all private methods */ /* Any and all static methods */ }

Example Lets program (in pairs) a class for a circle, Circle.java Have getter and setter for private member data Have an area computation Have a computation to determine if two circles overlap Program a simple test to exercise all of the methods of circle

Abstract Data Types Abstraction is to distill a system to its most fundamental parts. Applying the abstraction paradigm to the design of data structures gives rise to abstract data types (ADTs). An ADT is a model of a data structure that specifies the type of data stored, the operations supported on them, and the types of parameters of the operations. This would essentially be the “public interface” of a class An ADT specifies what each operation does, but not how it does it Lets repeat, an ADT is the operations not the implementation! We will see that we can implement ADTs in many, many ways

Interfaces and Abstract Classes The main structural element in Java that enforces an application programming interface (API) is an interface. An interface is a collection of method declarations with no data and no bodies. Interfaces do not have constructors and they cannot be directly instantiated. When a class implements an interface, it must implement all of the methods declared in the interface. An abstract class also cannot be instantiated, but it can define one or more common methods that all implementations of the abstraction will have.

Interface example public interface Robot { void sense(World w); void plan(); void act(World w); }

Use implements to enforce the interface public class Roomba implements Robot { /* code specific to Roomba */ public void sense(World w) {/* Roomba’s don’t sense */} public void plan() {/* code for roombas actions */} public void act(World w) {/* code to power motors */} }

Inheritance A mechanism for a modular and hierarchical organization is inheritance. This allows a new class to be defined based upon an existing class as the starting point. The existing class is typically described as the base class, parent class, or superclass, while the newly defined class is known as the subclass or child class. There are two ways in which a subclass can differentiate itself from its superclass: A subclass may specialize an existing behavior by providing a new implementation that overrides an existing method. A subclass may also extend its superclass by providing brand new methods. Used to support run-time polymorphism

Advanced Programming techniques

Exceptions Exceptions are unexpected events that occur during the execution of a program. An exception might result due to an unavailable resource, unexpected input from a user, or simply a logical error on the part of the programmer. In Java, exceptions are objects that can be thrown by code that encounters an unexpected situation. An exception may also be caught by a surrounding block of code that “handles” the problem. If uncaught, an exception causes the virtual machine to stop executing the program and to report an appropriate message to the console.

Catching Exceptions The general methodology for handling exceptions is a try-catch construct in which a guarded fragment of code that might throw an exception is executed. If it throws an exception, then that exception is caught by having the flow of control jump to a predefined catch block that contains the code to apply an appropriate resolution. If no exception occurs in the guarded code, all catch blocks are ignored. … try { /*Code that may generate exception*/ } catch(ExceptionType1 e1) { catch(ExceptionType2 e2) {

Throwing Exceptions Exceptions originate when a piece of Java code finds some sort of problem during execution and throws an exception object. This is done by using the throw keyword followed by an instance of the exception type to be thrown: throw new ExceptionType(parameters);

The throws Clause When a method is declared, it is possible to explicitly declare, as part of its signature, the possibility that a particular exception type may be thrown during a call to that method. The syntax for declaring possible exceptions in a method signature relies on the keyword throws (not to be confused with an actual throw statement). public static int parseInt(String s) throws NumberFormatException;

Casting Casting with Objects allows for conversion between classes and subclasses. A widening conversion occurs when a type T is converted into a “wider” type U: T is a type and U is a superclass/superinterface of T Example: Shape s = new Circle();

Casting A narrowing conversion occurs when a type T is converted into a “narrower” type S. S is a type and T is a superclass/superinterface of S A narrowing conversion of reference types requires an explicit cast. Example: Circle c = (Circle)s;

Generic Programming Generic Programming is a programming paradigm where the programmer programs interfaces and algorithms without a specific object hierarchy in mind. Rather the programmer only worries about operations (methods) needed to support an interface or perform an algorithm Java includes support for writing generic classes and methods, called Generics The actual type parameters are later specified when using the generic class/method as a type elsewhere in a program. Determined at compile-time not run-time!

Syntax for Generics Types can be declared using generic names: public class Node<E> { private E e; private Node<E> next; /* Rest of linked structure */ } They are then instantiated using actual types: Node<String> head = new Node<>(); There is not much to it actually, but it is a very strange thought process that you do not know what E is as you write it.

Nested Classes Java allows a class definition to be nested inside the definition of another class. The main use for nesting classes is when defining a class that is strongly affiliated with another class. This can help increase encapsulation and reduce undesired name conflicts. Nested classes are a valuable technique when implementing data structures, as an instance of a nested use can be used to represent a small portion of a larger data structure, or an auxiliary class that helps navigate a primary data structure.

Exercise With a team, program a generic singly-linked list class with a generic nested node class that supports integer size() boolean isEmpty() addFirst(e) removeFirst(e)