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 Type Cause of Exception
ArithmeticExceptionion Caused by math errors such as division by zero
ArrayIndexOutOfBoundsExcept
ion Caused by array indexes
ArrayStoreException 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
NullPointerException Caused by referencing a null object
Try Block
Statement that causes an
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
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.