Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
73 views

OOP With Java

1) Object-oriented programming focuses on modeling real-world problems using objects that contain both data and methods. 2) A class defines the form and behavior of objects, including their data fields and methods. Objects are instances of classes. 3) Key principles of OOP include encapsulation, inheritance, and polymorphism. Encapsulation hides implementation details and separates interfaces from implementations. Inheritance allows new classes to inherit attributes from existing classes. Polymorphism allows different classes to implement the same methods in different ways. 4) Java supports OOP and is portable, robust, secure, and supports advanced concepts like threads. The Java compiler produces bytecode that runs on a Java Virtual Machine, providing portability

Uploaded by

lemajambo7
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
73 views

OOP With Java

1) Object-oriented programming focuses on modeling real-world problems using objects that contain both data and methods. 2) A class defines the form and behavior of objects, including their data fields and methods. Objects are instances of classes. 3) Key principles of OOP include encapsulation, inheritance, and polymorphism. Encapsulation hides implementation details and separates interfaces from implementations. Inheritance allows new classes to inherit attributes from existing classes. Polymorphism allows different classes to implement the same methods in different ways. 4) Java supports OOP and is portable, robust, secure, and supports advanced concepts like threads. The Java compiler produces bytecode that runs on a Java Virtual Machine, providing portability

Uploaded by

lemajambo7
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 35

Chapter One

Introduction to Object-Oriented Programming


What is Object-Oriented Programming?
Object Oriented Programming (OOP) is a different method of thinking about programming. In
procedural programming (structured), we think about methods and the execution flow through
these methods. We think separately about data and how the methods interact with data.
Object-Oriented Programming, however, forces us to think in terms of objects and the interaction
between objects. An object is a self-contained entity that describes not only certain data, but also
the procedures to maintain the data.
The basic problem solving method in OOP is slightly different from the procedural approach. In
procedural approach, a problem is decomposed into sub-problems and this process is repeated
until the subtasks can be coded. In contrast, in addition to this, an object oriented approach
identifies the keywords in the problem. The keywords would be the object in the implementation
and the hierarchy defines the relationship between these objects. The term object is used here to
describe a limited well defined structure, containing all the information about some entity-data
type and methods-to manipulate the data.
Why do we use Object-Oriented Programming?
OOP enable us to model real-world problem through programs in more logical manner
Because objects are discrete entities, we can debug, modify and maintain them more
easily
If our objects are thoughtfully designed, we can reuse much of our code than is the case
with procedural programming.
Why Java?
Java is the fastest growing programming language in the world. Companies such as IBM and Sun
have adopted Java as the major application-development language. There are several reason for
this. First, Java is a modern OOP. The designers of Java spent much time studying the features
of classical OOP languages such as Smalltalk and C++, and made a successful effort to
incorporate the good features and omit the less desirable ones.
Second, Java is secure, robust and portable. That is, Java language
Enables the construction of virus-free, tamper-free system (Secure)
Supports the developments of programs that do not overwrite memory (Robust)
Yields programs that can be run on different types of computers without change
(Portable)
Third, Java supports the use of advanced programming concepts such as threads. A thread is a
process that can run concurrently with other processes.
Fourth and finally, Java bears a superficial resemblance to C++. Thus, it is easy for a C++
programmer to learn Java and for a Java programmer to learn C++. However, compared to C++,
Java is easier to use and learn, and is less error prone, more portable and better suited to the
internet.
OOP with Java

In the negative side, Java runs more slowly than most modern programming languages because it
is interpreted. To understand this, let us see the Java Virtual Machine (JVM) and the Byte code.
The Java Virtual Machine and the Byte Code
Compilers usually translate a higher level language into the machine language of a particular
type of computer. However, the Java compiler translates Java not into machine language but into
a pseudo machine language called Java Byte code.
Byte code is the machine language for imaginary Java computer. To run Java byte code on a
particular computer, you must install a JVM on that computer.
JVM is a program that behaves like a computer. Such a program is called an interpreter.

Typical Java environment


Let us see what will happen in each phase:
A: Program is created in an editor and stored on disk in a file ending with .java.
B: Compiler crates bytecodes and stores them on disk in a file ending with .class
C: Class loader reads .class files containing bytecodes from disk and puts those bytecodes
in memory
D: Bytecode verifier confirms that all bytecodes are valid and do not violate Java‟s
security restrictions.
E: Interpreter reads bytecodes and translates them into a language that the computer can
understand, possibly storing data values as the program executes.

2
OOP with Java

Basic Concept of OOP


Introduction to Classes and Objects
Classes
A class is user-defined data type that is used to implement an abstract object, giving us the
capability to use OOP with Java. A class includes members. A member can be either data known
as a data member or a method, know as a member method.
Objects
An object is a self-contained abstraction of an item. The item could be a student record,
employee record, a customer record or any screen window. An object includes all the data
necessary to represent the item and the methods that manipulate the data. The perfect object
knows everything about itself, including how to get input, give output and manipulate its data.
Otherwise, an object is an instance of a class. It can be uniquely identified by its name and it
defines a state that is represented by the values of its attribute at a particular point of time.
Members
A class has one or more variable types, called members. The two types of members are data
members and member methods.
Data members: data members of a class are exactly like the variables in structures.
E.g., class car{
String name;// data member
Color color;
}
Member methods: are methods/ functions defined within a class that act on the data
members in the class.
E.g., class First{
void new_line()//this is a member method
{
System.out.println();
System.out.println(“Hello”);
}
}
Class member visibility
Each member function and data member of a class has an attribute known as its visibility.
A class member‟s visibility determines who can use the member. Java has three levels of
visibility as follows.
 public
 private
 protected
public and private visibilities will be discussed here. But protected visibility will be
presented in the inheritance section.

3
OOP with Java

E.g., class Employee{


private String empName;
private String address;
private String city;
}
Here, the data members of the Employee class are declared as private. Private members
can be accessed only by a member method of that class. They can‟t be accessed by a non-
member method; the data is hidden from the outside world.
E.g., class Employee{
public String empName;
public String address;
public Sring city;
}
This class contains the class visibility label public. By declaring a class member public,
we make that member accessible to both member and nonmember methods.
Encapsulation, inheritance and polymorphism
* Data hiding and Encapsulation
What is Data hiding?
A goal of OOP is to differentiate the use of an object from the implementation of that
object. One method to accomplish this is through the usage of data hiding. Data hiding
enable us to completely encapsulate an object‟s data members. Data hiding prevents the
users of an object from directly accessing the data members of the class. The usage of
data hiding provides the following benefits.
 Users of the class are isolated from the actual representation of the data.
 Class programmers can change how data is represented or even, where data
comes from, without affecting applications that use the class.
The data-hiding paradigm does not allow non-member methods to access data members.
It is a good programming practice to make our entire data members private while
defining a good interface for the object.
Inheritance
Inheritance is a technique for creating a new class from an existing class by adding more
functionality to it. We say that the new class inherits all the functionality from the
existing class.
Polymorphism
Is the ability of a reference to a class to designate objects of its own class as well as its
derived class. The term polymorphism is derived from a Greek term meaning many
forms.

4
OOP with Java

Chapter Two
The Inside of Objects and Classes: More OOP Concepts.
Member Functions and Their Components
Class Declaration
class is a java keyword and all the normal keyword restrictions apply. One way of
thinking about a java class is to note that they resemble structures. We simply use the key
word class instead of struct, and the member of the structure become private by default.
the class declaration syntax is:
class class_name{
data_members;
...
class_methods();
...;
}
Instantiation & Initializing class objects.
The process of creating an object from a class is called instantiation. To create an object
from a java class, one must use the „new’ keyword.
Object Creation
No object is actually created by the declaration process. An object declaration simply
declares the name (identifier), which we use to refer to an object. E.g.,:
Account account; designate that the name account is used to refer to an account object,
but the actual Account object is not yet created. We create an object by invoking the new
command. The syntax is:
<object name> = new <class name>(<arguments>);
Where <object name> is the name of a declared object, <class name> is the name of the
class to which the object belongs, and <argument> is a sequence of values passed to the
method.
let us see the distinction between object declaration and object creation/instantiation.

A. Account account; State of memory


after A is executed
account
The identifier account is
declared and placed in memory

B. account = new Account(); State of memory


after B is executed
account
*
An account object is created
and the identifier account is Account
set to refer to it

5
OOP with Java

Customer customer;
customer = new Customer();
customer = new Customer();
What do you think will happen? An error? No. it is possible to use the same name to refer to
different objects of the same class.
consider the following figure:
customer
*

Customer Customer

Created with Created with


the first new the second new
Since there is no reference to the first customer object anymore, it will eventually be
erased and returned to the system. Remember that when an object is created, a certain
amount of memory space is allocated for storing objects. If this allocated but unused
space is not returned to the system for other use, the space gets wasted. This returning of
space to the system is called deallocation, and the mechanism to deallocate unused space
is called garbage collection.
Constructors
A constructor is a special initialization method that is called automatically whenever an
instance of a class is created. The constructor member method has, by definition, the
same name as the corresponding class. The constructor has no return value specification,
not even void. The Java run-time system makes sure that the constructor of a class is
called when instantiating an object.
Constructors are used to initialize the data members of the class. If we have data
members that must be initialized, we must have a constructor. In our constructor, we
should not do something that might fail because; the constructor does not return a value.
Default (Non-Parameterized) constructors
Let us look at the following example.
public class Employee{
private String empName;
private String address;
public Employee()
{
empName = “”;
address = “”;
}
}//end class
The constructor Employee() is a default or a non-parameterized constructor, because it
declares no parameters.

6
OOP with Java

Parameterized constructors
The parameterized constructors can accept values into the constructor that has different
parameters in the constructor. The value would be transferred from the main() method to
the constructor either with direct values or through variables.
Using overloaded constructors
Overloaded constructors enable object of a class to be initialized in different ways. To
overload constructors, simply provide multiple constructor declarations with different
parameter lists.
Attempting to overload a constructor with another constructor that has the exact same
signature (name and parameters) is a syntax error.
for instance, consider the constructors of the following class:
public class Person{
private String firstName;
private String secondName;
private int age;
public Person()
{
this(“No first name”, “No second name”,0);
}
public Person(String fName)
{
this(fName, “No second name”,0);
}
public Person(String fName,String sName)
{
this(fName,sName,0);
}
public Person(String fName,String sName,int a)
{
firstName = fName;
secondName = sName;
age = a;
}
public Person(Person person)
{
this(person.firstName,person.secondName,person.age);
}
}//end class

7
OOP with Java

The above class contains five overloaded constructors that provide convenient ways to
initialize objects of class person. Each constructor guarantees that every object the
constructor initializes begins in a consistent state.
The above class uses the keyword this to call / invoke a specific constructor with the
specified number and type of argument. It is a syntax error, when the „this’ reference is
used in a constructor‟s body to call another constructor of the same class and that
statement is not the first statement in the constructor. It is also a syntax error when a non-
constructor method attempts to invoke a constructor directly via the „this’ reference.
Methods
Methods (sometimes called functions or procedures) allow the programmer to modularize
a program by separating its tasks into self-contained units. These units are sometimes
called programmer defined methods.
A method is invoked or called by a method call. The method call specifies the name of
the method and provides information (arguments) that the called method requires to
perform its task. When the method call completes, the method either returns a result to
the calling method (or caller) or simply returns the control to the caller.
The first line of the method declaration is called the method header. Following the
method header, declaration and statements in brace form the method body, which is a
block. Variables can be declared in any block, and blocks can be nested. A method can’t
be declared inside another method.
the basic format of a method declaration is :
return-value-type method-name(para1,para2,...,paraN)
{
declarations and statements;
}
The method-name is any valid identifier. The return-type is the type of the result returned
by the method to the caller. The return-type void indicates that a method does not return a
value. Methods can return at most one value.
E.g., public double maximum(double x,double y,double z)
{
return Math.max(x,Math.max(y,z));
}
Access specifiers and methods
Access specifiers are used to restrict access to the method. Regardless of what the access
specifier is, the method is accessible from any other method in the same class. However,
although all methods in a class are accessible by all other methods in the same class,
there are certain necessary tasks that you might not want other objects to be able to
perform.
Let us see the access specifiers of Java language; public, private and protected.

8
OOP with Java

public: the public modifier is the most relaxed possible for a method. By specifying a
method as public, it becomes accessible to all classes regardless of their lineage or their
package;
protected: any class that extends the current class can access protected members. But
other classes which are not related to the current class in an inheritance can‟t make use of
the protected members of the current class. If you didn‟t assign a modifier in front of a
class declaration, the class is created with the default properties. By default, all classes
are assigned to package level visibility. This means that while the class may be extended
and employed by other classes, only those objects within the same package may make
use of this class.
private: private is the highest degree of protection that can be applied to a method. A
private method is only accessible by those methods in the same class. Even classes that
extend from the current class do not have access to a private member.
Other important concepts :
final: final classes may not have any subclasses and are created by placing the modifier
final in front of the class declaration. A variable can be decaled as final. Doing so
prevents its contents from being modified. This means that you must initialize a final
variable when it is declared. (In this usage, final is similar to const in C++).
abstract: an abstract class is a class that is incomplete, or to be considered incomplete.
Only abstract classes may have an abstract method. That is, methods that are declared but
not yet implemented. If a class that is not abstract contains an abstract method, then a
compile-time error occurs. A class has abstract methods if any of the following is true; if:
it explicitly contains a declaration of an abstract method. it inherits an abstract method
from its direct superclass.
An abstract class is defined with the modifier abstract. No instance can be created from
an abstract class. consider the following example:

the keyword abstract abstract public class Student{


here denotes an abstract class protected String name;
protected String courseGrade;
public Student()
{ this(“No Name”); }
public Student(String studName)
{
name = studName;
courseGrade = “NG”;
}
here the keyword abstract public void computeCourseGrade();
denotes an abstractmethod public String getCourseGrade()
{

9
OOP with Java

return courseGrade;
}
public String getName()
{
return name;
}
}//end class
An abstract method is a method with the keyword abstract and it ends with a semicolon
instead of a method body. We say a method is implemented if it has a method body.
Accessors and Mutators. / get() and set() Methods
private fields can be manipulated only by methods of the class in which the fields are
declared. Classes often provide public methods to allow clients of the class to set (i.e.,
assign values to) or get (i.e., obtain the values of) private instance variables. These
methods need not be called set and get, but they often are. Set methods are also
commonly called mutator methods (because they typically change a value). Get methods
are also commonly called accessors or query methods.
If an instance variable is declared public, the instance variable can be read or written at
will by any method that has reference to an object of the class in which the instance
variable is declared.
Using a public set and get method ensures that the new value is appropriate for that data
item. For example, an attempt to set the day of the month for a data to 37 would be
rejected; an attempt to set a person‟s weight to a negative value would be rejected, and so
on. So, although set and get methods could provide access to private data, the access is
restricted by the programmer‟s implementation.
Calling and returning: methods
Generally, the calling method controls method calls and their order. The called method is
controlled by the calling method.
Let us see an example:
public class First{
public void next_fun()
{
System.out.println(“Inside next_fun()”);
}
public void third_fun()
{
System.out.println(“inside third_fun()”);
}
}//end class
public class TestFirst{
public static void main(String args[])
{

10
OOP with Java

First fr = new First();


fr.next_fun();
fr.third_fun();
System.out.println(“main() is compleated”);
}
}//end class
Passing values to methods
Java provides two methods for passing variables between methods. We will see passing
by value and passing by address in the following section.
Passing by value
Here, the actual variable will not be passed; rather, the value of the variable is passed to
the receiving method. Because the value/copy of the variable is passed to the receiving
method, the receiving method can‟t modify the calling method‟s variable.
Consider the following program that calculates the factorial of a give number. The
example illustrates passing by value.
import java.io.*;
public class Factorial{
public void calcFact(int n)
{
int i,fact=1;
for(int i=1;i<=n;i++)
fact*=i;
System.out.println(“the factorial of ”+n+ “is ”+fact);
}
}//end class

public class TestFactorial{


public static void main(String args[])
{
Factorial fact = new Factorial();
InputStreamReader reader = new InputStreamReader(System.in);
BufferedReader input = new BufferedReader(reader);
String num = input.readLine();
int n = Integer.parseInt(num);
fact.calcFact(n);
}
}//end class

11
OOP with Java

Passing by address
When we pass an argument (local variable) by address, the variable‟s address is assigned
to the receiving method‟s parameter. The address of the variable not its value is copied to
the receiving method‟s parameter when we pass a variable address. In Java, all the arrays
are passed by address.
Passing arrays to methods
Java automatically passes arrays to methods using simulated call-by reference; the called
methods can modify the element values in the callers, the original values. The value of
the name of the array is the address of the first element of the array. Because the starting
address of the array is passed, the called method knows precisely where the array is
stored.
Although entire array are passed simulated call-by-reference yet the individual array
elements are passed call-by-value, exactly as simple variables are. For a method to
receive an array through a method call, the method‟s parameter list must specify that an
array would be received.
E.g., public class ArrayEg{
public void modifyArray(int num[])
{ for(int i=0;i<num.length;i++)
num[i]+=2;
System.out.println(“inside modifyArray()”);
for(int i=0;i<num.length;i++)
System.out.println(num[i]+” ”);
}}//end class
public class TestArray{
public static void main(String args[])
{
int a[] = new int[10];
for(int i=0;i<a.length;i++)
a[i]=i+1;
System.out.println(“inside main()”);
for(int i=0;i<a.length;i++)
System.out.print(a[i]+ “ ”);
ArrayEg aEg = new ArrayEg();
System.out,println();
aEg.modifyArray(a);
System.out.println();
System.out.println(“back inside main()”);
for(int i=0;i<a.length;i++)
System.out.print(a[i]+ “ ”);
} }//end class

12
OOP with Java

Method return values


When we want to return a value from a method to its calling method, we put the return
value after the return statement.
Do not return global variables. There would not be any need to do so because their values
are already known thought the code.
Static versus instance members
Each object has its own copy of all the instance variables of a class. In certain cases, only
one copy of a particular variable should be shared by all objects of a class. A static field-
called a class variable- is used in such case, among others. A class variable represents
class-wide info- all objects of the class share the same piece of data. The declaration of a
static member begins with the keyword static.
Although class variables may seem like global variables, class variables have class scope.
A class‟s public static member can be accessed through a reference to any object of that
class, or they can be accessed by qualifying the member name with the class name and a
dot (.), as in Math.random(). A class‟s private static class member can only be accessed
through methods of that class. Actually, static class member exist even when no object of
that class exist- they are available as soon as the class is loaded into memory at execution
time. To access a private static member when no object of the class exists, a public static
method must be provided and the method must be called by qualifying its name with the
class name and a dot. Consider the following example.
public class Employee{
private String firstName;
private String secondName;
private static int count1=0;
public static int count2=0;
public Employee(String fName,String sName)
{
firstName=fName;
secondName=sName;
count1++;
count2++;
}
public String getFirstName()
{Return firstName; }
public String getSecondName()
{ Return secondName; }
public static int getCount()
{ Return count1; }
}//end class

13
OOP with Java

public class TestStatic{


public static void main(String args[])
{
System.out.println(“using public method:”+Employee.getCount());
System.out.println(“using public var:”+Employee.count2);
Employee e2 = new Employee(“Saba”,”Getachew”);
Employee e2 = new Employee(“Zeritu”,”Kebede”);
System.out.println(“using public method:”+e1.getCount());
System.out.println(“using public var:”+e2.count2);
System.out.println(“After instantiation:”+Employee.getCount());
System.out.println(“After instantiation:”+Employee.count2);
System.out.println(“accessing instance members”);
System.out.println(“employee1:”e1.getFirstName()+”
“+e1.getSecondName());
System.out.println(“employee2:”e2.getFirstName()+ “
”+e2.getSecondName());
}
}//end class
NB: A method declared static can‟t access a non-static class member. Unlike nonstatic methods,
a static method has no “this” reference because static variables and static methods exist
independent of any object of a class whether or not any objects of the class have been
instantiated.

14
OOP with Java

Chapter Three
Inheritance
In inheritance, a new class is defined by means of an older, pre-existing class. This leads
to a situation in which, the new class has all the functionality of the older, pre-existing
class and, additionally, introduces its own specific functionality. We say the new class
inherits the functionality of another existing class.
While speaking of inheritance, the existing class is called the superclass (base class) and
the new class is called subclass (derived class).
Concept of Inheritance
One advantage of OOP is the re-usage of code. The capability to define custom data
types using classes enables us to reuse the code that we develop. This works well if we
always need exactly the same object. In real world, however, we may need an object that
is almost similar to an already developed object but not exactly similar. Inheritance
enables us to reuse an object more quickly; thus making slight adjustments where
necessary.
Superclasses and subclasses
Often, an object of one class “is an” object of another class as well. For instance, in
geometry, a rectangle is a quadrilateral. Thus, in Java, class rectangle can be said to
inherit from class Quadrilateral. Because every subclass object “is an” object of its
superclass, and one superclass can have many subclasses, the set of objects represented
by a superclass typically is larger than the set of objects represented by any of its
subclasses. For example, the superclass vehicle represents all vehicles, including cars,
trucks, boats and so on. By contrast, subclass car represents a smaller, more specific
subset of all vehicles.
Inheritance relationship forms tree-like hierarchical structure

to specify that class TwoDimensionalShape extends (or inherits from) class Shape, class
TwoDimensionalShape could be declared in Java as follows:
public class TwoDimensionalShape extends Shape

15
OOP with Java

Objects of all classes that extend a common superclass can be treated as objects of that
superclass. (i.e., such objects have an “is-a” relationship with the superclass). However,
superclass objects can‟t be treated as objects of their subclasses. For example, all cars are
vehicles, but not all vehicles are cars.
Protected Members
A superclass‟s protected members can be accessed by members of that superclass, by
members of any class derived from that superclass and by members of other classes in the
same package. (Protected members have package access).
Overriding a method
If a class declares an instance method, then the declaration of that method is said to
override any and all methods with the same signature in the superclass.
If a method declaration overrides the declaration of another method, then a compile-time
error occurs if they have different return types or if one has a return type and the other is
void.
The access modifier of the overriding method must provide at least as much access as the
overridden method, or a compile-time error occurs. on more detail:
 If the overridden method is public, then the overriding method must be public;
otherwise, a compile-time error occurs.
 If the overridden method is protected, then the overriding method must be
protected or public, otherwise, a compile-time error occurs.
 If the overridden method has default (package) access, the overriding method
must not be private; otherwise, a compile-time error occurs.
Notice that a private method is never accessible and so can‟t be overridden in the
technical sense of these terms.
Using this () and super ()
Because you frequently want to call the superclass‟s constructor explicitly, there is a
keyword in Java that makes this possible. super() will call the parent‟s constructor which
has the appropriate supplied parameters. It is also possible to have more than one
constructor for a class (which was discussed in the overloading section). If you are
creating more than one constructor, you typically do not want to duplicate the common
code. So you can call a same class constructor using this() keyword, sending any required
parameters.
The keyword super() has two general forms. The first is call of superclass constructor.
The second is used to access a member of the superclass that has been hidden by a
member of the subclass. let us see each use of the super keyword one by one:
public class Student{
private String name;
private int age;
public Student(String name, int age)
{

16
OOP with Java

this.name = name;
this.age = age;
}
public void printData()
{
System.out.println(“Name->”+name);
System.out.println(“Age->”+age);
}
}//end class

public class MakeStudent extends Student{


int roll;
double avgMark;
public MakeStudent(String name,int age,int roll, double avgMark)
{
super(name,age);//calling superclass constructor
this.roll=roll;
this.avgMark=avgMark;
}
public void printMark()
{
System.out.println(“Roll No->”+roll);
System.out.println(“Average Mark->”+avgMark);
}
}//end class

public class TestStudent{


public static void main(String args[])
{
MakeStudent clsStud = new MakeStudent(“Ruth Leta”,15,100,65);
clsStud.printData();
clsStud.printMark();
}
}//end class
The second form of super keyword is somewhat similar to that of this pointer. The
difference is, super() always refers to the superclass of the subclass in which it is used.
This usage has the following general form:
super.member;

17
OOP with Java

Here, member can either be a method or an instance variable. This second form of super()
is most applicable to situations in which member names of a subclass hide members by
the same name in the superclass. Consider the following example.
public class ClassA{
int i;
}//end class

public class ClassB extends ClassA{


int i;//this i hides the i in class ClassA
public ClassB(int a,int b)
{
super.i = a;//i in ClassA
i = b;//i in ClassB
}
public void show()
{
System.out.println(“i in superclass : ”+super.i);
System.out.println(“i in subclass : ”+i);
}
}//end class

public class TestSuper{


public static void main(String args[])
{
ClassB clsB = new ClassB(10,20);
clsB.show();
}
}//end class
Although the instance variable i in ClassB hides the i in ClassA, super allows access to
the i defined in the superclass. Super can also be used to call methods that are hidden by
subclasses.
Use of final with Inheritance
A class can be declared final if its definition is complete and no subclasses are desired or
required. A compile-time error occurs if the name of a final class appears in the extends
clause of another class declaration; this implies that a final class can‟t have any
subclasses.
The keyword final has three uses. First, it can be used to create the equivalent of a named
constant. The other two uses of final apply to inheritance. Both are examined here:

18
OOP with Java

Final keyword prevents overriding. To disallow a method from being overridden, specify
final as a modifier at the start of its declaration. Methods declared as final can‟t be
overridden. Have a look at the following example.
public class ClassA{
public final void firstMethod()
{
System.out.println(“this is a final method declared only once”);
}
}//end class
public class ClassB extends ClassA{
public void firstMethod()
{
System.out.println(“illegal to declare this method again”);
}
}//end class
Final prevents inheritance. Sometimes, you will want to prevent a class from being
inherited. To do this, precede the class declaration with the keyword final. Declaring a
class as final implicitly declares all of its methods as final too. Consider the following
example.
public final clas ClassA{
//…
}//end class
public class ClassB extends ClassA{//illegal inheritance
}//end class
Constructors in subclasses
Instantiating a subclass object begins a chain of constructor calls in which the subclass
constructor, before performing its own tasks, invokes its direct superclasse‟s constructor
either explicitly (via the super reference) or implicitly (calling the superclasse‟s default
constructor or no-argument constructor). Similarly, if the superclass was derived from
another class, the superclass constructor would be required to invoke the constructor of
the next class up in the hierarchy, and so on. The last constructor called in the chain is
always the constructor of class Object. The original subclass constructor‟s body finishes
executing last.

19
OOP with Java

Chapter Four
Polymorphism
Polymorphism allows programmers to send the same message to objects from different
classes. i.e., in its simplest from, polymorphism allows a single variable to refer to
objects from different classes.
Polymorphism enables us to “program in the general” rather than “program in the
specific”. In particular, polymorphism enables us to write programs that process objects
of classes that are part of the same class hierarchy as if they are all objects of their
classes.
With polymorphism, it is possible to design and implement systems that are easily
extensible. New classes can be added with little or no modification to the generic portions
of the program, as long as those classes are part of the inheritance hierarchy that the
program processes generically. The only parts of a program that must be altered to
accommodate new classes are those program components that require direct knowledge
of the new classes that the programmer adds to the hierarchy.
Relationships among Objects in an inheritance hierarchy
Here, we will examine the relationships among classes in a hierarchy. In this section, we
see that an object of a subclass can be treated as object of its superclass. This enables
various interesting manipulations. For example, a program can create an array of
superclass reference that refers to objects of many subclass types. This is allowed despite
that fact that the subclass objects are of different types, because each subclass object is an
object of its subclasses. However, a superclass object is not an object of any of its
subclasses. The “is-a” relationship applies only from a subclass to its direct and indirect
superclasses.
Assigning reference of a subclass to a superclass-type variable
Let us see an example here:
public class Point3{
private int x;
private int y;
public Point3()
{
}
public Point3(int xValue,int yValue)
{
x=xValue;
y=yValue;
}
public void setX(int xValue)
{

20
OOP with Java

x=xValue;
}
public void setY(int yValue)
{
y=yValue;
}
public int getX()
{
return x;
}
public int getY()
{
return y;
}
public String toString()
{
return “[“+getX()+ “, ”+getY()+ “]”;
}
}//end class
public class Circle4 extends Point3{
private double radius;
public Circle4(int xValue, int yValue, double rValue)
{
super(xValue,yValue);
setRadius(rValue);
}
public void setRadius(double rValue)
{
radius = (rValue < 0.0?0.0:rValue);
}
public double getRadius()
{
return radius;
}
public double getDiameter()
{
return 2*getRadius();
}
public double getCircumfrence()
{

21
OOP with Java

return Math.PI*getDiameter();
}
public double getArea()
{
return Math.PI*getRadius()*getRadius();
}
public String toString()
{
return “Center = “+super.toString()+ “; Radius=”+getRadius();
}
}//end class

import javax.swing.*;
public class PolyTest1{
public static void main(String args[])
{
Point3 point = new Point3(30,50);
Circle4 circle = new Circle4(120,89,2.7);
String output = “Call Point3‟s toString with superclass”+
“reference to superclass object:\n”+ point.toString();
output+= “\n\nCall Circle4‟s toString with subclass ”+
“reference to subclass object:\n”+circle.toString();
Point3 pointRef = circle;
Output+= “\n\ncall Circle4‟s toString with superclass ”+
“ refernce to subclass object:\n “+pointRef.toString();
JOptionPane.showMessageDialog(null,output);
System.exit(0);
}
}//end class
In the above program, the statement Point3 pointRef = circle; assigns the reference of
subclass object circle to superclass-type variable pointRef. A superclass-type variable
that contains a reference to a subclass object calls the subclass method; hence,
pointRef.toString() actually calls class Circle4‟s toString method. The Java compiler
allows this “crossover” because an object of a subclass is an object of its superclass.
Assigning a superclass object’s reference to a subclass-type variable
Let us consider the following example:
public class PolyTest2{
public static void main(String args[])
{
Point3 point = new Point3(30,50);

22
OOP with Java

Circle4 circle;//subclass-type variable


//assign superclass reference to subclass-type variable
circle = point;
}
}//end class
If you run this program, it will generate an error. Because the assignment is not allowed
(incompatible type). The Java compiler prevents this assignment, because a Point3 is not
a Circle4- the “is-a” relationship applies only between the subclass and its superclass.
It turn out that the Java compiler does allow this assignment if we explicitly cast the
superclass reference to the subclass type. In programs that process superclass and
subclass objects by using superclass reference, only methods of the superclass can be
invoked via the superclass reference. Casting superclass reference to subclass reference
(also known as downcasting) enables a program to invoke subclass functionality to
perform subclass-specific operations on subclass objects.
N.B. assigning the reference of a superclass object to a subclass-type variable (without an
explicit cast) is a compile-time error
Subclass Method calls via superclass-type variables
Consider the following program:
public class PolyTest3{
public static void main(String args[])
{
Point3 point;
Circle circle = new Circle4(120,89,2.7);
point = circle;//aim superclass reference at subclass object.
int x = point.getX();
int y = point.getY();
point.setX(10);
point.setY(20);
point.toString();
//attempt to invoke subclass-only (Circle4) method on
//subclass object through superclass (Point3) reference
double radius = point.getRadius();
point.setRadius(33.33);
double diameter = point.getDiameter();
double circumference = point.getCircumfrence();
double area = point.getArea();
}
}//end class

23
OOP with Java

In the above code, we have such an assignment: point = circle; Java compiler allows this
because a Circle4 is a Point3 object. Using point reference, we can only invoke
superclass only methods. But when we try to invoke subclass only methods using point,
the Java compiler generates error on each of these lines, because these are not methods of
the superclass Point3. (in this case, using a Point3 variable, we can invoke only Point3
methods getX, getY, setX, setY and toString)
Summary of the allowed assignments between superclass and subclass variables
Despite the fact that a subclass object also is a superclass object, the subclass and
superclass objects are indeed different. As we have discussed previously, subclass objects
can be treated as if they were superclass objects. This is a logical relationship, because
the subclass contains all the members of the superclass, but the subclass can have
additional subclass-only members. For this reason, assigning a superclass reference to a
subclass-type variable is not allowed without an explicit cast; such an assignment would
leave the subclass-only members undefined for the subclass object.
We have discussed four ways to assign superclass and subclass references to variables of
superclass and subclass types:
1. Assigning a superclass reference to a superclass-type variable is straight forward
2. Assigning a subclass reference to a subclass-type variable is straight forward.
3. Assigning a subclass object’s reference to a superclass type variable is safe,
because the subclass object is an object of its superclass. However, this reference
can be used to invoke only superclass methods. If this code refers to subclass-only
members through the superclass variable, the compiler generates an error.
4. Attempting to assign a superclass object’s reference to a subclass type variable is
a compile-time error. To avoid the error, the superclass reference must be cast to a
subclass type explicitly.
Multiple inheritance and Interfaces
An interface is like a class that can‟t be instantiated. Its purpose is to specify a set of
requirements for a class to implement. These requirements are regarded as a “contract”
between the implementing class and any client class that uses it.
An interface is a description of a capability. It lists the methods that a class must
implement to carry out that capability.
An interface typically consists of declarations of related methods, although an interface
also may contain static and final fields that represent constants. In any case, all interface
members are public. A class that implements an interface typically provides definitions
for the methods declared in the interface.
A class that implements an interface must provide an implementation for all the method
signatures in the interface. An interface declaration introduces a new reference type
whose members are constants and abstract methods.

24
OOP with Java

An interface is typically used in place of an abstract class when there is no default


implementation to inherit. i.e., no instance variables and no default methods
implementations.
A compile-time error occurs if the identifier naming an interface appears as the name of
any other class or interface in the same package.
All interface methods are abstract regardless of whether the term abstract occurs. In more
basic terms, an interface is abstract because an interface can‟t be instantiated as an object.
Let us see an example here:
public interface Shape{
public double getArea();
public double getVolume();
public String getName();
}//end interface
public class Point extends Object implements Shape{
private int x;
private int y;
public Point(int xValue,int yValue)
{
x = xValue;
y = yValue;
}
public void setX(int xValue)
{
x=xValue;
}
public void setY(int yValue)
{
y=yValue;
}
public int getX()
{
return x;
}
public int getY()
{
return y;
}
public double getArea()
{
return 0.0;

25
OOP with Java

}
public double getVolume()
{
return 0.0;
}
public String getName()
{
return “Point”;
}
public String toString()
{
return “[”+getX()+ “, ”+getY()+ “]”;
}
}//end class
Use the Circle4 program and the following Cylinder class for the coming illustration
public class Cylinder extends Circle4{
private double height;
public Cylinder(int x,int y,double radius,double heightValue)
{
super(x,y,radius);
setHeight(heightValue);
}
public void setHeight(double heightValue)
{
height = (heightValue <0.0?0.0:heightValue);
}
public double getHeight()
{
return height;
}
public double getArea()
{
return 2 * super.getArea() + getCircumfrence() * getHeight();
}
public double getVolume()
{
return super.getArea() * getHeight();
}
public String getName()
{

26
OOP with Java

return “Cylinder”;
}
public String toString()
{
return super.toString()+ “; Height = ” + getHeight();
}
}//end class
import javax.swing.*;
import java.text.*;
public class InterfaceTest{
public static void main(String args[])
{
DecimalFormat twoDigits = new DecimalFormat(“0.00”);
Point point =new Point(7,11);
Circle4 circle = new Circle4(22,8,3.5);
Cylinder cylinder = new Cylinder(20,30,3.3.3,10.75);
String output = point.getName()+ “:”+point+ “\n”+ circle.getName() +
“:”+circle+ “\n”+ cylinder.getName() + “:”+cylinder+ “\n”;
Shape arrayOfShapes[] = new Shape[3];//create shape array
arrayOfShape[0] = point;
arrayOfShape[1] = circle;
arrayOfShape[2] = cylinder;
for(int i=0; i<arrayOfShapes.length;i++)
{
output += ”\n\n ”+arrayOfShapes[i].getName()+ “:” +
arrayOfShapes[i].toString()+ “\nArea =
”+twoDigits.format(arrayOfShapes[i].getArea())+ “\nVolume = ”+
twoDigits.format(arrayOfShapes[i].getVolume());
}
JOptionPane.showMessageDialog(null,output);
System.exit(0);
}
}//end class
When a class implements an interface, the same “is-a” relationship provided by
inheritance applies. For example, class Point implements Shape. Therefore, a Point object
is a Shape. In fact, objects of any class that extends Point are also Shape object.
Multiple inheritances
A class can be derived from more than one superclass. This concept is called multiple
inheritance. But such a notion can‟t be directly used in Java. Therefore, one has to use an

27
OOP with Java

interface if a class is expected to inherit behaviors from more than one superclass. For
instance, Let us see the declaration of class Point:
public class Point extends Object implements Shape{
}//end class
In Java, all classes inherit from class Object. So whether we write the statement “Point
extends Object” or not, the Java compiler processes the inheritance relationship among
Point and Object classes. Therefore, our class Point will have both the functionality of
class Object and that of Shape, hence multiple inheritance. The point to be underlined
here is, multiple inheritance is only possible through the use of interfaces.
To summarize the discussion of interface; lets see the following comparison.
Unlike a class, an interface:
Declares only method headers and public constants;
Has no constructors
Can‟t be instantiated
Can be implements by a class
Can‟t be implemented by an interface
Can‟t extends a class
Can extend several other interfaces.
Interface are very useful for specifying what a class should be able to do, while deferring
to a later time how the contract should be implemented. But in some cases, interfaces are
too restrictive. They allow no variable definitions (except public final constants) or
executable statements. Often, it is better to proceed with a partial class implementation,
deferring only those methods that depend directly upon the backing data structure. That is
when an abstract class should be used.

28
OOP with Java

Chapter Five
Exception Handling
What is an exception?
An exception is an error that occurs during the execution of a program. Java facilitates
the management of such errors by diverting control to special program bocks that are
called exception handlers.
Exception handling enables programmers to create applications that can resolve (or
handle) exceptions. In many cases, handling an exception allows a program to continue
executing as if no problem had been encountered. These features enable programmers to
write robust and fault-tolerant programs.
Exception-Handling Overview
Program logic frequently tests conditions that determine how program execution should
proceed. Consider the following psudocode;
Perform a task
If the preceding task did not execute correctly
Perform error processing
Perform next task
If the proceeding task did not execute correctly
Perform error processing

In this psudocode, we begin by performing a task; then, we test whether that task
executed correctly or not. If not, we perform error processing. Otherwise, we continue
with the next task. Although this form of error handing works, intermixing program logic
with error-handling logic can make the program difficult to read, modify and debug-
especially in large applications. Intermixing program and error-handling logic can
degrade a program‟s performance, because the program must test the error-handling logic
to determine whether the next task can be performed.
Exception handling enables the programmer to remove error-handling code from the
“main line” of the program‟s execution, which improves program clarity and enhances
modifiability.
The causes of exception
An exception is thrown for one of the three reasons:
(a) An abnormal execution condition was synchronously detected by the JVM. Such conditions
arise because:
 Evaluation of an expression violates the normal semantics of the Java language, such
as an integer divided by zero.
 An error occurs in loading or linking part of the Java program
 Some limitation at recourse is executed, such as using too much memory
(b) A throw statement was executed in Java code

29
OOP with Java

(c) An asynchronous exception occurred either because


 The method stop of class Thread was invoked
 An internal error has occurred in the virtual machine.
The Throwable class Hierarchy
A Java exception is an instance of the Throwable class or one of its extensions. Such an
object can be instantiated by running program in two ways. Either explicitly by a throw
statement in the program, or implicitly by the Java run-time system when it is unable to
execute a statement in the program.
When an exception is thrown, it can be caught by a catch clause of a try statement. Using
a try statement to catch an exception is called exception handling.

There are two kinds of exceptions: the kind that you can prevent by writing better code,
and the kind that you can‟t. The first kind is called unchecked exceptions. They are
instances of the Error class, the run-timeException class, and their extensions. For
example, if the division of an integer by zero is attempted, the system will generate an
ArithmeticException.
Exceptions of the second kind are called checked exceptions because they are “checked”
by the compiler before the program is run. Statements that throw them either must be
placed within a try statement, or they must be declared in their method‟s header. Checked
exceptions are the kind that should be expected and therefore managed by an exception
handler.

30
OOP with Java

Handling of an exception
Java provides try statement to enable exception handling. A try statement consists of
keyword try, followed by braces ({}) that delimit a try block. The try block contains
statements that might cause exceptions and statements that should not execute if an
exception occurs. At least one catch clause (also called an exception handler) or a finally
clause must immediately follow the try block. Each catch clause specifies in parenthesis,
an exception parameter that identifies the exception type the handler can process. The
exception parameter‟s name enables the catch clause to interact with a caught exception
object. After the last catch handler, an optional finally clause provides code that always
execute, whether or not an exception occurs. A finally clause is an ideal location for code
that releases resources to prevent “resource leaks”.
The general try statement in Java has this syntax:
try{
statements;
}catch(exception-type1 idetifier1){
statements;
}catch(exception-type2 identifier2){
statements;
}
...
finally{
statements;
}
The point in the program at which an exception occur (i.e., the location where a method
detects and throws an exception) is called the throw point. If an exception occurs in a try
block, the try block terminates immediately and program control transfers to the first
catch clause that follows the try block. This is known as the termination model of
exception handling, because the try block that encloses a thrown exception terminates
when the exception occurs. When a try block terminates, local variables declared in the
block go out of scope. Next the program searches for the first catch that can process the
type of exception that occurred. The program locates the matching catch by comparing
the thrown exception’s type with each catch’s exception-parameter type until the
program finds a match. A match occurs if the types are identical or if the thrown
exception‟s type is a subclass of the exception parameter‟s type. When a match occurs,
the code contained within the matching catch handler executes. When a catch clause
finishes processing, local variables declared within the catch clause (including the catch
parameter) go out of scope. Any remaining catch clauses that correspond to the try block
are ignored and execution resumes at the first line of code after the try/catch sequence.

31
OOP with Java

If no exceptions occur in a try block, the program ignores the catch handler(s) for that
block. If a finally clause appears after the last catch clause, the finally clause executes
regardless of whether an exception occurs.
If an exception occurs in a method and is not caught, or the statement that caused the
exception is not in a try block, the method that contains the statement terminates
immediately, and the program attempts to locate an enclosing try block in the calling
method. This process is called stack unwinding.
let us consider how to handle an exception using try-catch statement:
try{
num1 = Integer.parseInt(n1);
num2 = Integer.parseInt(n2);
}
catch(NumberFormatException nfe){
JOptionPane.showMessageDialog(null,nfe.getMessage());
}
another code fragment that handles an ArithmeticException is
try{
ans = num1/num2;
JOptionPane.showMessageDialog(null,ans);
}
catch(ArithmeticException ae){
JOptionPane.showMessageDialog(null,ae.getMessage());
}
The other way of exception handling is by using the keyword throws. This keyword is
used along methods. If a method is capable of raising an exception that it does not handle,
it must specify that the exception should be handled by the calling method. This is done
by the throws keyword.
let us see an example here:
try{
num1 = Integer.parseInt(firstNumber);
num2 = Integer.parseInt(secondNumber);
result = quotient(num1,num2);//throws an ArithmeticException
}
catch(NumberFormatException nfe){
JOptionPane.showMessageDialog(null,nfe.getMessage());
}
catch(ArithmeticException ae){
JOptionPane.showMessageDialog(null,ae.getMessage());
}
...

32
OOP with Java

private int quotient(int nume,int deno) throws ArithmeticException


{
return nume/deno;
}
In the above code, the private method called quotient is declared with the keyword
throws in the method header definition. This shows that the statement return nume/deno;
in the body of the method is capable of throwing an ArithmeticException. But, there is no
mechanism to handle the exception inside the method body. Therefore, the method
calling this method should have a means to handle the exception.
The throw statement
The throw statement causes an exception to be thrown. The result is an immediate
transfer of control that may exit multiple statements until a catch clause is found that
catches the thrown value.
The throw statement takes a single argument, an object of throwable class.
syntax: throw ThrowableInstance
let us consider a simple example here:
public class ThrowDemo{
public static void main(String args[])
{
try{
throw new ArithmeticExcepion();
}
catch(ArithmeticException ae){
System.out....here
}
}
}//end class
The finally clause
Programs that obtain certain types of resources must return those resources to the system
explicitly to avoid so-called resource leaks. In programming languages such as C and
C++, the most common kind of resource leak is a memory leak. Java performs automatic
garbage collection to remove objects no longer used by programs, thus avoiding most
memory leaks. However, other types of resource leaks can occur in Java. For example,
files, database connections and network connections that are not closed properly might
not be available for use in other programs, or even later in the same program‟s execution.
Java guarantees that a finally clause (if one is present following a try/catch sequence) will
execute whether or not an exception is thrown in the corresponding try block or in any of
its corresponding catch clauses. Java also guarantees that a finally clause (if one is
present) will execute if a try block exits by using a return, break or continue statement.

33
OOP with Java

Resource-release code typically is places in a finally clause. Suppose a resource is


allocated in a try block. If no exception occurs, the catch handlers are skipped and control
proceeds to the finally clause, which frees the resource. Control proceeds to the first
statement after the finally clause. If an exception does occur, the program skips the rest of
the try block. If the program catches the exception in one of the catch handlers, the
program processes the exception. Then the finally clause release the resource and control
proceeds to the first statement after the finally clause.
If an exception that occurs in the try block can‟t be caught by one of that try block‟s catch
handlers, the program skips the rest of the try block and control proceeds to the finally
clause, which releases the resource. Then the program passes the exception up the call
(i.e., to the calling method), which attempts to catch it. This process can occur many
times.
If a catch handler throws an exception, the finally clause still executes. Then an exception
is passed o the calling method.
User Defined Exceptions
There might be situations in which you want to handle exceptions that are not available in
the exception classes of Java. Suppose you accept a user name and a password from a
user. While verifying this information, if the login credentials do not match, you may
need to generate an exception. For this purpose, you can use a user defined exception.
A new exception class must extend an existing exception class to ensure that the class can
be used with exception handling mechanism. Like any other class, an exception class can
contain fields and methods. The subclass of the exception class inherits the methods
provided by the Throwable class because Throwable is the superclass for the Exception
class.
let us consider an example here:
package javaexception;
/**
*
*
*/
public class UserDefinedException extends Exception{
/** Creates a new instance of UserDefinedException */
public UserDefinedException() {
System.out.println("Wrong data has been entered");
}
public UserDefinedException(String msg)
{
System.out.println(msg);
}
}

34
OOP with Java

package javaexception;
/**
*
*/
public class UserTrial {
private int num1,num2;
/** Creates a new instance of UserTrial */
public UserTrial(int a,int b)
{
num1=a;
num2=b;
}
public void show() throws UserDefinedException
{
if(num1<0 || num2>0)
throw new UserDefinedException("Wrong data has been entered");
else
System.out.println("You entered : "+num1+" and "+num2);
}
}

package javaexception;
/**
*
*/
public class Main {
/** Creates a new instance of Main */
public Main() {
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
UserTrial trial = new UserTrial(-1, 1);
try{
trial.show();
}catch(UserDefinedException ude){
System.err.println("Illegal values entered");
}
}
}

35

You might also like