Data Structures and Algorithms in JAVA Chapter 2

  • Slides: 31
Download presentation
Data Structures and Algorithms in JAVA Chapter 2

Data Structures and Algorithms in JAVA Chapter 2

Object Oriented Design Goals Objects : a well defined entity which is a specification

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

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

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

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 -

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

Hierarchical Organization

Design Patterns It describes the main elements of a solution in an abstract way

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 -

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

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

- Object Creation and Referencing S x = new S(); // x reference to

- Object Creation and Referencing S x = new S(); // x reference to object of type S x. a(); // call a method using dot operator 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

Using Inheritance in Java There are two primary ways of using inheritance of classes

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 person{ get. Name(); }; class student extends person{ get. GPA () ; // extended method to student class }

Types of Method Overriding Refinement : additional functionality to the code ( constructor of

Types of Method Overriding Refinement : 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

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 pay. Rate; public

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

class Hourly. Employee extends Employee { private int hours; public Hourly. Employee(String h. Name,

class Hourly. Employee extends Employee { private int hours; public Hourly. Employee(String h. Name, double h. Rate) { super(h. Name, h. Rate); hours = 0; } public void add. Hours(int more. Hours) {hours += more. Hours; } public double pay() {return pay. Rate * 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

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 Type Cause of Exception Arithmetic. Exceptionion Caused by math errors

Common Java Exceptions Exception Type Cause of Exception Arithmetic. Exceptionion Caused by math errors such as division by zero Array. Index. Out. Of. Bounds. Exception Caused by array indexes Array. Store. Exception Caused when a program tries to store the wrong type of data in an array IOException Caused by general I/O failures, such as inability to read from file Null. Pointer. Exception Caused by referencing a null object

Try Block Statement that causes an exception Throws exception object Catch Block Exception handler

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

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

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

Example : Class Error 3 { public static void main(string args[]) { int a=10;

Example : Class Error 3 { 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 (Arithemtic. Exception 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

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

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 objectoriented languages, such as Smalltalk and C++, allow

Mixin : Unlike Java, some objectoriented 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 An abstract class: a class that contains empty method

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 class A { abstract void

Example: Abstract class // A Simple demonstration of 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 Abstract. Demo { public static void main(String args[]) { B b = new B(); b. callmetoo(); } }

Strong Typing By enforcing that all variables be typed and that methods declare the

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

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

Casting Exception Number n; Integer i; n = new Integer(3); if (n instanceof 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

 A Generics generic type is a type that is not defined at compilation

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