Data Structures and Algorithms in JAVA Chapter 2.

Slides:



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

1 Lecture 11 Interfaces and Exception Handling from Chapters 9 and 10.
ITEC200 – Week03 Inheritance and Class Hierarchies.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Fall 2007CS 2251 Inheritance and Class Hierarchies Chapter 3.
March 2004Object Oriented Design1 Object-Oriented Design.
Chapter 3 Data Abstraction: The Walls. © 2005 Pearson Addison-Wesley. All rights reserved3-2 Abstract Data Types Modularity –Keeps the complexity of a.
Review of Object-Oriented Concepts in JAVA Object-Oriented Concepts supported by JAVA. Advantages of Object-Orientation. Inheritance. Abstract Classes.
Fall 2007CS 2251 Inheritance and Class Hierarchies Chapter 3.
© 2006 Pearson Addison-Wesley. All rights reserved4-1 Chapter 4 Data Abstraction: The Walls.
1 Chapter 6 Inheritance, Interfaces, and Abstract Classes.
Review of Object-Oriented Concepts in JAVA Object-Oriented Concepts supported by JAVA. Object-Oriented Concepts supported by JAVA. Advantages of Object-Orientation.
© 2006 Pearson Addison-Wesley. All rights reserved4-1 Chapter 4 Data Abstraction: The Walls.
Chapter 10 Classes Continued
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter N - 1 Chapter 13 Polymorphism is-a relationships Interfaces.
Appendix A.2: Review of Java and Object-Oriented Programming: Part 2 “For the object-oriented project, remember that the primary unit of decomposition.
220 FINAL TEST REVIEW SESSION Omar Abdelwahab. INHERITANCE AND POLYMORPHISM Suppose you have a class FunClass with public methods show, tell, and smile.
Introduction to Object-oriented programming and software development Lecture 1.
CISC6795: Spring Object-Oriented Programming: Polymorphism.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Object Oriented Design. OOP Object Oriented programming (OOP) is the idea of developing programs by defining objects that interact with each other Java.
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.
Features of Object Oriented Programming Lec.4. ABSTRACTION AND ENCAPSULATION Computer programs can be very complex, perhaps the most complicated artifact.
Inheritance. Introduction Inheritance is one of the cornerstones of object-oriented programming because it allows the creation of hierarchical classifications.
Inheritance - Polymorphism ITI 1121 Nour El Kadri.
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.
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 5 Creating Classes.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Object Oriented Programming
Object-Oriented Programming © 2013 Goodrich, Tamassia, Goldwasser1Object-Oriented Programming.
Introduction to Object-Oriented Programming Lesson 2.
COM S 228 Introduction to Data Structures Instructor: Ying Cai Department of Computer Science Iowa State University Office: Atanasoff.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Inheritance and Class Hierarchies Chapter 3. Chapter Objectives  To understand inheritance and how it facilitates code reuse  To understand how Java.
Object orientation and Packaging in Java Object Orientation and Packaging Introduction: After completing this chapter, you will be able to identify.
Inheritance ndex.html ndex.htmland “Java.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
Author: DoanNX Time: 45’.  OOP concepts  OOP in Java.
BY:- TOPS Technologies
9.1 CLASS (STATIC) VARIABLES AND METHODS Defining classes is only one aspect of object-oriented programming. The real power of object-oriented programming.
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
CH 1-4 : INTRODUCTION ACKNOWLEDGEMENT: THE SLIDES ARE PREPARED FROM SLIDES PROVIDED WITH DATA STRUCTURES AND ALGORITHMS IN C++, GOODRICH, TAMASSIA AND.
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
Lecture 8 D&D Chapter 9 Inheritance Date.
Modern Programming Tools And Techniques-I
Data Abstraction: The Walls
Inheritance ITI1121 Nour El Kadri.
Object-Oriented Programming
Ch. 2 Object-Oriented Programming
Inheritance-Basics.
Inheritance and Polymorphism
Java Programming Language
Chapter 11: Inheritance and Polymorphism
Lecture 2 of Computer Science II
Object-Oriented Programming: Polymorphism
Object Oriented Programming
Object-Oriented Programming
Object-Oriented Programming
OOP and ADTs Chapter 14 Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved.
Object-Oriented Programming: Polymorphism
Review of Object-Oriented Concepts in JAVA
Extending Classes.
Java Programming Language
Week 6 Object-Oriented Programming (2): Polymorphism
Java Inheritance.
Review of Object-Oriented Concepts in JAVA
Final and Abstract Classes
Oriented Design and Abstract Data Type
Presentation transcript:

Data Structures and Algorithms in JAVA Chapter 2

Object Oriented Design Goals Objects : a well defined entity which is a specification of the data fields, also called instance variables, as well as the methods (operations) that the object can execute. Classes : are an excellent example of an object This view of computing is intended to fulfill several goals and incorporate several design principles, which we discuss in this chapter.

Object-Oriented Design Goals Robustness : Correct program is not enough, it has to be robust. ( handling unexpected errors) Adaptability : Programs needs to be able to evolve over time in response to changing conditions in its environment portability, ability of software to run with minimal change on different hardware and operating system platforms.using Java is a key to fulfill this goal. Reusability : same code should be usable as a component of different systems in various applications. Reduce the cost

Object-Oriented Design Principles Abstraction : distill a complicated system down to its most fundamental parts and describe these parts in. - Defines function but not implementation - Abstract Data Type (ADT) ! Data and operations on that data ! Operations are specified with a defined interface ! Specify what and not how You will use classes to design ADTs this quarter

Encapsulation : different components of a software system should not reveal the internal description Information hiding User does not need to know how something is done, just that it is done. Objects encapsulate data and operations Functions encapsulate actions tails of their respective implementations. Modularity : Modularity refers to an organizing principle for code in which different components of a software system are divided into separate functional units

Benefits of Modularity Program construction - Team work - Easier to manage Debugging - Isolates errors - Debug each module as you go easy to locate bugs Reading the program Modifying the program Eliminating redundant code

Hierarchical Organization

Design Patterns It describes the main elements of a solution in an abstract way that can be specialized for a specific problem at hand. Pattern Components: 1. Name; which identifies the pattern. 2. Context; which describes the scenarios for which this pattern can be applied. 3. Template; which describes how the pattern is applied 4. Result; which describes and analyzes what the pattern produces.

Groups of Patterns: 1. Patterns for solving algorithm design problems. - Recursion - Divide-and-conquer 2. Patterns for solving software engineering problems. - Iterator - Adapter - Template method

Inheritance and Polymorphism ◦ Inheritance: Java allows related classes to be organized in a hierarchical manner using the extends keyword.

Polymorphism: Same code behaves differently at different times during execution. This is due to dynamic binding. S x = new S (); x.a(); // call the S version of this method x= new T(); x.a(); // call the T version of this method, object x took more than one meaning - Object Creation and Referencing S x = new S(); // x reference to object of type S x.a(); // call a method using dot operator

Using Inheritance in Java There are two primary ways of using inheritance of classes in Java, specialization and extension Specialization : specializing a general class to particular subclasses class shape{ area(); // general formula}; class oval extends shape { area () // special formula to calculate oval area} class rectangle extends shape { area() // special formula to calculate rectangle area } Extension : add new methods that are not present in the super class class person{ getName();}; class student extends person{ getGPA () ; // extended method to student class }

Types of Method Overriding Refinement : add additional functionality to the code ( constructor of subclasses calls the constructor of superclass using super key word and then adds additional functionality to it) Replacement : completely replaces the method of the superclass that it is overriding ( area () methods for oval and rectangle class are totally different from area() method belongs to superclass Shape)

The Keyword this When this program is executed, it prints the following: The dog local variable =5.0 The dog field = 2

Review of inheritance class Employee { protected String name; protected double payRate; public Employee(String name, double payRate) { this.name = name; this.payRate = payRate; } public String getName() {return name;} public void setPayRate(double newRate) { payRate = newRate; } public double pay() {return payRate;} public void print() { System.out.println("Name: " + name); System.out.println("Pay Rate: "+payRate); }

class HourlyEmployee extends Employee { private int hours; public HourlyEmployee(String hName, double hRate) { super(hName, hRate); hours = 0; } public void addHours(int moreHours) {hours += moreHours;} public double pay() {return payRate * hours;} public void print() { super.print(); System.out.println("Current hours: " + hours); }

Exceptions An Exception is a condition that is caused by a run- time error in the program. The purpose of exception handling mechanism is to provide a means to detect and report an “exceptional circumstances” so that appropriate action can be taken. Exception handling mechanism 1. Find the problem (Hit the exception) 2. Inform that an error has occurred (Throw the exception) 3. Receive the error information (Catch the exception) 4. Take corrective actions (Handle the exception)

Common Java Exceptions Exception TypeCause of Exception ArithmeticExceptionionCaused by math errors such as division by zero ArrayIndexOutOfBoundsExceptionCaused by array indexes ArrayStoreExceptionCaused when a program tries to store the wrong type of data in an array IOExceptionCaused by general I/O failures,such as inability to read from file NullPointerExceptionCaused by referencing a null object

Try Block Statement that causes an exception Try Block Statement that causes an exception Catch Block Statement that handles the exception Catch Block Statement that handles the exception Exception Object Creator Exception handler Throws exception object

---- try { statements; // generate an exception } catch (Exception-type e) { statements; // processes the exception } ----

Example : Class Error3 { public static void main(string args[]) { int a=10; int b=5; int c= 5; int x, y; try { x= a / (b-c); // Exception Here } Catch (ArithemticException e) { System.Out.println( “Division by Zero”); } y = a / (b+c); System.Out.println( “y = ” + y); } }

Interfaces and Abstract Classes The main structural element in Java that enforces an API is the interface. An interface is a collection of method declarations with no data and no bodies.

Multiple Inheritance in Interfaces extending from more than one class is known as multiple inheritance. In JAVA, multiple inheritance is allowed for interfaces but not for classes Multiple Inheritance causes confusion. Class A Void Area(int a); Class B Void Area(int a); Class C C x = new C(); x. Area(3); // this will arise a problem, which area to bind?

Mixin : Unlike Java, some object-oriented languages, such as Smalltalk and C++, allow for multiple inheritance of concrete classes, not just interfaces. In such languages, it is common to define classes, called mixin classes, that are never intended to be created as stand-alone objects, but are instead meant to provide additional functionality to existing classes

Abstract Classes and Strong Typing Abstract Classes and Strong Typing An abstract class: a class that contains empty method declarations (that is, declarations of methods without bodies). An abstract class may not be instantiated, that is, no object can be created from an abstract class. subclass of an abstract class must provide an implementation for the abstract methods of its superclass, unless it is itself abstract. No matter the inheritance hierarchy, at the end we must define the methods in the abstract class.

Example: Abstract class // A Simple demonstration of abstract. abstract class A { abstract void callme(); // concrete methods are still allowed in abstract classes void callmetoo() { System.out.println("This is a concrete method."); } } class B extends A { void callme() { System.out.println("B's implementation of callme."); } } class AbstractDemo { public static void main(String args[]) { B b = new B(); b.callme(); b.callmetoo(); } }

Strong Typing By enforcing that all variables be typed and that methods declare the types they expect and return, Java uses the technique of strong typing to help prevent bugs.

Casting and Generics Widening Casting : A widening conversion occurs when a type T is converted into a "wider" type U. T and U are class types and U is a superclass of T T and U are interface types and U is a superinterface of T T is a class that implements interface U. Example: Integer i = new Integer(3); Number n = i; // widening conversion from Integer to Number Java.lang.Number Narrowing Conversions: A narrowing conversion occurs when a type T is converted into a "narrower" type S. T and S are class types and S is a subclass of T T and S are interface types and S is a subinterface of T T is an interface implemented by class S. Example: Number n = new Integer(2); // widening conversion from Integer to Number Integer i = (Integer) n; // narrowing conversion from Number to Integer

Casting Exception Number n; Integer i; n = new Integer(3); if (n instanceof Integer) i = (Integer) n; // This is legal n = new Double(3.1415); if (n instanceof Integer) i = (Integer) n; // This will not be attempted

Generics A generic type is a type that is not defined at compilation time, but becomes fully specified at run time.