CMP 301 Object Oriented Programming Langauage I
CMP 301 Object Oriented Programming Langauage I
COURSE CONTENTS
Basic OOP Concepts: classes, objects, inheritance, polymorphism, Data abstraction, tools for
developing, compiling, interpreting and debugging, java programs, java syntax and data
objects, operators. Central flow constructs, objects and classes programming, arrays, methods,
exception, applets and the abstract, OLE, persistence, window toolkit, laboratory exercises in
an OOP language.
OBJECTIVES:
1. To teach the student the concepts of object oriented and procedure programming.
2. To differentiate between the basic OOP concepts of classes, objects, methods,
encapsulation, inheritance, polymorphism, data abstraction and method overloading.
3. To implement the basic concepts of OOP.
4. To design applications using JAVA syntax and data objects.
5. To teach student to implement arrays, exception handling, applets, GUI and Windows.
LEARNING OUTCOMES
The students should be able to:
1. Differentiate the principles of object oriented programming and procedural
programming.
2. Outline the essential features and elements of the Java programming language.
3. Explain programming fundamentals, including statement and control flow and
recursion.
4. Codes basic programs in Java programming language.
Prints to the screen in Java language.
Makes relational operations in Java.
Constructs loops in Java.
Defines arrays in Java and uses them.
5. Uses objects and classes.
Declares objects and classes.
Distinguishes classes and objects.
Declares and uses variables.
Declares and uses methods and properties.
6. Lists the object-oriented programming concepts.
Explains and uses encapsulation.
Explains and uses inheritance.
Explains and uses polymorphism.
7. Names special functions.
Distinguishes constructors, default constructors, interfaces, abstract classes and
abstract methods.
Recognizes operator overloading functions.
Identifies base and derived classes.
8. Codes object-oriented programs.
Implements constructors, default constructors, interfaces, abstract classes and
abstract methods.
Overloads operators.
Inherits a class from another class.
Writes a complete program using object-oriented programming concepts.
9. Explains and handles exceptions.
Describes exceptions.
Throws exceptions
Catches exceptions.
10. Writes multithreaded Java programs.
Develops task classes by implementing the Runnable interface.
Creates threads to run tasks using the Thread class.
Controls threads using the methods in the Thread class.
Executes tasks in a thread pool.
11. Understands the concepts of database and database management systems.
Understands the relational data model: relational data structures, constraints,
and languages.
Uses SQL to create and drop tables and to retrieve and modify data.
Loads a driver, connects to a database, executes statements, and processes result
sets using JDBC.
12. Uses generic classes and methods.
Declares generic classes.
Uses generic classes.
Declares generic methods.
Uses generic methods.
TEXT BOOK(S):
1. Object Oriented Programming and Java by Danny Poo, Derek Kiong and Swarnalatha Ashok
2. Java How To Program (9ed.) Deitel.
instanceof Operator:
This operator is used only for object reference variables. The operator checks whether
the object is of a particular type(class type or interface type).
instanceof operator is written as:
(Object reference variable ) instanceof (class/interface type)
If the object referred by the variable on the left side of the operator passes the IS-A
check for the class/interface type on the right side, then the result will be true. Following
is the example:
String name = “James”;
boolean result = name instanceof String; // This will return true since name is type of
String.
This operator will still return true if the object being compared is the assignment
compatible with the type on the right. Following is one more
Example:
Class Vehicle{
}
public class Car extends Vehicle{
public static void main(String args[]){
Vehicle ab =new Car();
boolean result = ab instanceof Car;
System.out.println(result);
}
}
This would produce the following result:
True
3.0 CONTROL STRUCTURE
Normally, statements in a program are executed one after the other in the order in which they’re
written. This process is called sequential execution. Various Java statements, which we’ll soon
discuss, enable you to specify that the next statement to execute is not necessarily the next one
in sequence. This is called transfer of control.
Advantages of control structure in OOP
1. Shorter development times
2. More frequent on-time delivery of systems
3. More frequent within-budget completion of software projects.
All programs could be written in terms of only three control structures:
the sequence structure
the selection structure and
the repetition structure.
The sequence structure
The sequence structure is built into Java. Unless directed otherwise, the computer executes
Java statements one after the other in the order in which they’re written—that is, in sequence.
The selection structure
Java has three types of selection statements.
The if-single selection statement either performs (selects) an action, if a condition is
true, or skips it, if the condition is false.
Example:
Class SingleSelection{
public static void main(String args[]){
int grade;
if(grade>=60)
System.out.println(“passed”);
}
}
The if…else double selection statement performs an action if a condition is true and
performs a different action if the condition is false.
Class DoubleSelection{
public static void main(String args[]){
int grade;
if(grade>=60){
System.out.println(“passed”);
}else{
System.out.println(“failed”);
}
}
}
The switch multiple selection statement performs one of many different actions,
depending on the value of an expression.
Example:
Class Switch{
public static void main(String args[]){
int grade;
switch (grade){
case 1:
if(grade>=70)
System.out.println(“A”);
break;
case 2:
if(grade>=60)
System.out.println(“B”);
break;
case 3:
if(grade>=50)
System.out.println(“C”);
break;
case 4:
if(grade>=45)
System.out.println(“D”);
break;
default:
System.out.println( "F" );
break;
}
}
The repetition structure
Java provides three repetition statements (also called looping statements) that enable programs
to perform statements repeatedly as long as a condition (called the loop-continuation condition)
remains true. The repetition statements are
the while
do…while and
for statements
Output:
1234
Broke out of loop
Continue statement
The continue statement, when executed in a while, for or do…while, skips the remaining
statements in the loop body and proceeds with the next iteration of the loop. In while and
do…while statements, the program evaluates the loop-continuation test immediately after the
continue statement executes. In a for statement, the increment expression executes, then the
program evaluates the loop-continuation test.
Example:
1 // ContinueTest.java
2 // continue statement terminating an iteration of a for statement.
3 public class ContinueTest
4{
5 public static void main( String[] args )
6{
7 for ( int count = 1; count <= 10; count++ ) // loop 10 times
8{
9 if ( count == 5 ) // if count is 5,
10 continue;
11 System.out.printf( "%d ", count );
12 } // end for
13 System.out.println( "\nUsed continue to skip printing 5" );
14 } // end main
15 } // end class ContinueTest
Output:
1 2 3 4 6 7 8 9 10
Used continue to skip printing 5
4.0 PRINCIPLES OR FEATURES OF OOP
1. Objects, instance variables, classes and methods
Object - An object is an instance of a class. Objects have states and behaviors.
Example: A dog has states - color, name, breed as well as behavior such as wagging
their tail, barking, eating.
Instance Variables - Each object has its unique set of instance variables. An object's
state is created by the values assigned to these instance variables.
Class- A class can be defined as a template/blueprint that describes the
behavior/state that the object of its type supports.
Methods - A method is basically a behavior. A class can contain many methods. It
is in methods where the logics are written, data is manipulated and all the actions
are executed.
2. Encapsulation
Encapsulation is one of the four fundamental OOP concepts. The other three are
inheritance, polymorphism, and abstraction.
Encapsulation is the technique of making the fields in a class private and providing access
to the fields via public methods. If a field is declared private, it cannot be accessed by
anyone outside the class, thereby hiding the fields within the class. For this reason,
encapsulation is also referred to as data hiding.
Encapsulation can be described as a protective barrier that prevents the code and data being
randomly accessed by other code defined outside the class. Access to the data and code is
tightly controlled by an interface.
The main benefit of encapsulation is the ability to modify our implemented code without
breaking the code of others who use our code. With this feature Encapsulation gives
maintainability, flexibility and extensibility to our code.
Example: Let us look at an example that depicts encapsulation:
/* File name: EncapTest.java */
public class EncapTest{
private String name;
private String idNum;
private int age;
public int getAge(){
return age;
}
Public String getName(){
return name;
}
Public String getIdNum(){
return idNum;
}
Public void setName(String newName){
name = newName;
}
Public void setIdNum(String newIdNum){
idNum = newIdNum;
}
Public void setAge(int newAge){
age = newAge;
}
The public methods are the access points to this class' fields from the outside java world.
Normally, these methods are referred as getters and setters. Therefore any class that wants
to access the variables should access them through these getters and setters. The variables
of the EncapTest class can be access as below:
/* Run EncapTest.java */
public static void main(String args[]){
EncapTest encap =new EncapTest();
encap.setName("James");
encap.setAge(20);
encap.setIdNum("12343ms");
System.out.print("Name : "+ encap.getName()+" Age : "+ encap.getAge());
}
}
This would produce the following result:
Name:JamesAge:20
3. Data abstraction
Abstraction refers to the ability to make a class abstract in OOP. An abstract class is one
that cannot be instantiated. All other functionality of the class still exists, and its fields,
methods, and constructors are all accessed in the same manner. You just cannot create an
instance of the abstract class. If a class is abstract and cannot be instantiated, the class does
not have much use unless it is subclass. This is typically how abstract classes come about
during the design phase. A parent class contains the common functionality of a collection
of child classes, but the parent class itself is too abstract to be used on its own.
An abstract class’s purpose is to provide an appropriate superclass from which other classes
can inherit and thus share a common design. When we think of a class, we assume that
programs will create objects of that type. Sometimes it’s useful to declare classes—called
abstract classes—for which you never intend to create objects. Because they’re used only
as superclasses in inheritance hierarchies, we refer to them as abstract superclasses. These
classes cannot be used to instantiate objects, because, as we’ll soon see, abstract classes are
incomplete. Subclasses must declare the “missing pieces” to become “concrete” classes,
from which you can instantiate objects.
Abstract Class:
Use the abstract keyword to declare a class abstract. The keyword appears in the class
declaration somewhere before the class keyword.
Abstract Methods:
If you want a class to contain a particular method but you want the actual implementation
of that method to be determined by child classes, you can declare the method in the parent
class as abstract.
The abstract keyword is also used to declare a method as abstract. An abstract method
consists of a method signature, but no method body. Abstract method would have no
definition, and its signature is followed by a semicolon, not curly braces as follows:
/* File name : Employee.java */
public abstract class Employee {
private String name;
private String address;
private int number;
public Employee(String name, String address, int number) {
System.out.println("Constructing an Employee");
this.name = name;
this.address = address;
this.number = number;
}
public double computePay() {
System.out.println("Inside Employee computePay");
return 0.0;
}
public void mailCheck() {
System.out.println("Mailing a check to "+this.name +" "+this.address);
}
public String toString() {
return name +" "+ address +" "+ number;
}
public String getName() {
return name;
}
public String getAddress() {
return address;
}
public void setAddress(String newAddress) {
address = newAddress;
}
public int getNumber() {
return number;
}
}
Notice that nothing is different in this Employee class. The class is now abstract, but it still
has three fields, seven methods, and one constructor. Now if you would try as follows:
/* File name : AbstractDemo.java */
public class AbstractDemo {
public static void main(String[] args) {
/* Following is not allowed and would raise error */
Employee e =new Employee("George W.","Houston, TX",43);
System.out.println("\n Call mailCheck usingEmployee reference--");
e.mailCheck();
}
}
Extending Abstract Class:
We can extend Employee class in normal way as follows:
/* File name : Salary.java */
public class Salary extends Employee {
private double salary;//Annual salary
public Salary(String name, String address, int number, double salary) {
super(name, address, number);
setSalary(salary);
}
public void mailCheck() {
System.out.println("Within mailCheck of Salary class ");
System.out.println("Mailing check to "+ getName()+" with salary "+ salary);
}
public double getSalary() {
return salary;
}
public void setSalary(double newSalary) {
if(newSalary >=0.0) {
salary = newSalary;
}
}
public double computePay() {
System.out.println("Computing salary pay for "+ getName());
return salary/52;
}
}
Here, we cannot instantiate a new Employee, but if we instantiate a new Salary
object, the Salary object will inherit the three fields and seven methods from
Employee.
/* File name : AbstractDemo.java */
public class AbstractDemo {
public static void main(String[] args) {
Salary s =new Salary("Mohd Mohtashim","Ambehta, UP", 3,3600.00);
Employee e =new Salary("John Adams","Boston, MA", 2,2400.00);
System.out.println("Call mailCheck using Salary reference --");
s.mailCheck();
System.out.println("\n Call mailCheck usingEmployee reference--");
e.mailCheck();
}
}
This would produce the following result:
Constructing an Employee
Constructing an Employee
Call mailCheck using Salary reference –
Within mailCheck of Salary class
Mailing check to MohdMohtashim with salary 3600.0
Call mailCheck using Employee reference—
Within mailCheck of Salary class
Mailing check to JohnAdams with salary 2400.
4. Polymorphism
Polymorphism is the ability of an object to take on many forms. The most common use of
polymorphism in OOP, occurs when a parent class reference is used to refer to a child class
object. Any Java object that can pass more than one IS-A test is considered to be
polymorphic.
In Java, all Java objects are polymorphic since any object will pass the IS-A test for their
own type and for the class Object. It is important to know that the only possible way to
access an object is through a reference variable. A reference variable can be of only one
type. Once declared, the type of a reference variable cannot be changed. The reference
variable can be reassigned to other objects provided that it is not declared final. The type
of the reference variable would determine the methods that it can invoke on the object. A
reference variable can refer to any object of its declared type or any subtype of its declared
type. A reference variable can be declared as a class or interface type.
Let us look at an example.
public interface Vegetarian{
}
public class Animal{
}
public class Deer extends Animal implements Vegetarian{
}
Now, the Deer class is considered to be polymorphic since this has multiple inheritance.
Following are true for the above example:
A Deer IS-A Animal
A Deer IS-A Vegetarian
A Deer IS-A Deer
A Deer IS-A Object
When we apply the reference variable facts to a Deer object reference, the following
declarations are legal:
Deer d =new Deer();
Animal a = d;
Vegetarian v = d;
Object o = d;
All the reference variables d,a,v,o refer to the same Deer object in the heap
Example:
public class Employee {
private String name;
private String address;
private int number;
public Employee(String name,String address,int number) {
System.out.println("Constructing an Employee");
this.name = name;
this.address = address;
this.number = number;
}
public void mailCheck() {
System.out.println("Mailing a check to "+this.name +" "+this.address);
}
public String toString() {
return name +" "+ address +" "+ number;
}
publicString getName() {
return name;
}
public String getAddress() {
return address;
}
public void setAddress(String newAddress) {
address = newAddress;
}
public int getNumber() {
return number;
}
}
public class Salary extends Employee {
private double salary;//Annual salary
public Salary(String name,String address,int number,double salary) {
super(name, address, number);
setSalary(salary);
}
public void mailCheck() {
System.out.println("Within mailCheck of Salary class ");
System.out.println("Mailing check to "+ getName() +" with salary "+
salary);
}
public double getSalary() {
return salary;
}
public void setSalary(double newSalary) {
if(newSalary >=0.0) {
salary = newSalary;
}
}
public double computePay() {
System.out.println("Computing salary pay for "+ getName());
return salary/52;
}
}
public static void main(String[] args) {
Salary s =new Salary("Mohd Mohtashim","Ambehta, UP", 3,3600.00);
Employee e =new Salary("John Adams","Boston, MA", 2,2400.00);
System.out.println("Call mailCheck using Salary reference --");
s.mailCheck();
System.out.println("\n Call mailCheck usingEmployee reference--");
e.mailCheck();
}
}
5. Method overloading
When a class has two or more methods by same name but different parameters, it is known
as method overloading. It is different from overriding. In overriding a method has same
method name, type, number of parameters etc. if number of parameters are same, then type
of parameters should be different.
Lets consider the example shown before for finding minimum numbers of integer type. If,
lets say we want to find minimum number of double type. Then the concept of Overloading
will be introduced to create two or more methods with the same name but different
parameters.
public class ExampleOverloading{
// for integer
public static int minFunction(int n1, int n2) {
int min;
if (n1 > n2) min = n2;
else min = n1;
return min;
}
// for double
public static double minFunction(double n1, double n2) {
double min;
if (n1 > n2) min = n2;
else min = n1;
return min;
}
public static void main(String[] args) {
int a = 11;
int b = 6;
double c = 7.3;
double d = 9.4;
int result1 = minFunction(a, b);
// same function name with different parameters
double result2 = minFunction(c, d);
System.out.println("Minimum Value = " + result1);
System.out.println("Minimum Value = " + result2);
}
}
This would produce the following result:
Minimum Value = 6
Minimum Value = 7.3
Overloading methods makes program readable. Here, two methods are given same name
but with different parameters.
6. Inheritance
Inheritance can be defined as the process where one object acquires the properties of
another. With the use of inheritance, the information is made manageable in a hierarchical
order. When we talk about inheritance, the most commonly used keyword would be
extends and implements. These words would determine whether one object IS-A type of
another. By using these keywords we can make one object acquire the properties of another
object.
Inheritance in java is a mechanism in which one object acquires all the properties and
behaviors of parent object.
The idea behind inheritance in java is that you can create new classes that are built upon
existing classes. When you inherit from an existing class, you can reuse methods and fields
of parent class, and you can add new methods and fields also.
IS-A Relationship:
IS-A is a way of saying: This object is a type of that object. Let us see how the extends
keyword is used to achieve inheritance.
Inheritance represents the IS-A relationship, also known as parent-child relationship.
Why use inheritance in java
For Method Overriding (so runtime polymorphism can be achieved).
For Code Reusability.
Syntax of Java Inheritance
class Subclass-name extends Superclass-name
{
//methods and fields
}
The extends keyword indicates that you are making a new class that derives from an
existing class.
In the terminology of Java, a class that is inherited is called a super class. The new class is
called a subclass.
class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
Output
Programmer salary is: 40000.0
Bonus of programmer is:10000
In the above example, Programmer object can access the field of own class as well as of
Employee class i.e. code reusability.
Types of inheritance in java
On the basis of class, there can be three types of inheritance in java: single, multilevel and
hierarchical.
In java programming, multiple and hybrid inheritance is supported through interface only.
We will learn about interfaces later.
public class Animal{
}
public class Mammal extends Animal{
}
public class Reptile extends Animal{
}
public class Dog extends Mammal{
}
Now, based on the above example, In Object Oriented terms the following are true:
Animal is the superclass of Mammal class.
Animal is the superclass of Reptile class.
Mammal and Reptile are subclasses of Animal class.
Dog is the subclass of both Mammal and Animal classes.
Now, if we consider the IS-A relationship, we can say:
Mammal IS-A Animal
Reptile IS-A Animal
Dog IS-A Mammal
Hence : Dog IS-A Animal as well
With use of the extends keyword the subclasses will be able to inherit all the properties of
the superclass except for the private properties of the superclass. We can assure that
Mammal is actually an Animal with the use of the instance operator.
public class Dog extends Mammal{
public static void main(String args[]){
Animal a =new Animal();
Mammal m =new Mammal();
Dog d =new Dog();
System.out.println(m instanceof Animal);
System.out.println(d instanceof Mammal);
System.out.println(d instanceof Animal);
}
}
This would produce the following result:
true
true
true
Since we have a good understanding of the extends keyword, let us look into how the
implements keyword is used to get the IS-A relationship.
The implements keyword is used by classes by inheritance from interfaces. Interfaces can
never be extended by the classes.
Example:
public interface Animal{
}
public class Mammal implements Animal{
}
public class Dog extends Mammal{
}
The instanceof Keyword:
Let us use the instanceof operator to check determine whether Mammal is actually an
Animal, and dog is actually an Animal
Example:
interfaceAnimal{
}
class Mammal implements Animal{
}
public class Dog extends Mammal{
public static void main(String args[]){
Mammal m =new Mammal();
Dog d =new Dog();
System.out.println(m instanceof Animal);
System.out.println(d instanceof Mammal);
System.out.println(d instanceof Animal);
}
}
This would produce the following result:
true
true
true
HAS-A relationship:
These relationships are mainly based on the usage. This determines whether a certain class
HAS-A certain thing. This relationship helps to reduce duplication of code as well as bugs.
Lets us look into an example:
public class Vehicle{
}
public class Speed{
}
public class Van extends Vehicle{
private Speed sp;
}
This shows that class Van HAS-A Speed. By having a separate class for Speed, we do not
have to put the entire code that belongs to speed inside the Van class which makes it
possible to reuse the Speed class in multiple applications.
In Object-Oriented feature, the users do not need to bother about which object is doing the
real work. To achieve this, the Van class hides the implementation details from the users
of the Van class. So basically what happens is the users would ask the Van class to do a
certain action and the Van class will either do the work by itself or ask another class to
perform the action. A very important fact to remember is that Java only supports only single
inheritance. This means that a class cannot extend more than one class. Therefore following
is illegal:
public class extends Animal, Mammal{
}
However, a class can implement one or more interfaces. This has made Java get rid of the
impossibility of multiple inheritance.
Has-A-Relationship (Aggregation in Java)
If a class have an entity reference, it is known as Aggregation. Aggregation represents
HAS-A relationship.
Consider a situation, Employee object contains many information such as id, name, emailId
etc. It contains one more object named address, which contains its own information such
as city, state, country, zipcode etc. as given below.
class Employee{
int id;
String name;
Address address; //Address is a class
...
}
In such case, Employee has an entity reference address, so relationship is Employee HAS-
A address.
Why use Aggregation?
For Code Reusability.
In this example, we have created the reference of Operation class in the Circle class.
class Operation{
int square(int n){
return n*n;
}
}
class Circle{
Operation op; //aggregation
double pi=3.14;
double area(int radius){
op=new Operation();
int rsquare=op.square(radius);//code reusability (i.e. delegates the method call).
return pi*rsquare;
}
public static void main(String args[]){
Circle c=new Circle();
double result=c.area(5);
System.out.println(result);
}
}
7. Packages
A java package is a group of similar types of classes, interfaces and subpackages. Package
in java can be categorized in two form, built-in package and user-defined package. There
are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc. Here,
we will have the detailed learning of creating and using user-defined packages.
Advantages of Java Package
1. Java package is used to categorize the classes and interfaces so that they can be
easily maintained.
2. Java package provides access protection.
3. Java package removes naming collision.
Simple example of java package
The package keyword is used to create a package in java.
//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
How to compile java package
If you are not using any IDE, you need to follow the syntax given below:
> javac -d directory javafilename
For example
>javac -d . Simple.java
The -d switch specifies the destination where to put the generated class file. You can use
any directory name like /home (in case of Linux), d:/abc (in case of windows) etc. If you
want to keep the package within the same directory, you can use . (dot).
How to run java package program
You need to use fully qualified name e.g. mypack.Simple etc to run the class.
To Compile: javac -d . Simple.java
To Run: java mypack.Simple
Output: Welcome to package
The -d is a switch that tells the compiler where to put the class file i.e. it represents
destination. The . represents the current folder.
How to access package from another package?
There are three ways to access the package from outside the package.
1. import package.*;
2. import package.classname;
3. fully qualified name.
Using packagename.*
If you use package.* then all the classes and interfaces of this package will be accessible
but not subpackages. The import keyword is used to make the classes and interface of
another package accessible to the current package.
Example of package that import the packagename.*
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello
Using packagename.classname
If you import package.classname then only declared class of this package will be accessible.
Example of package by import package.classname
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.A;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello
Using fully qualified name
If you use fully qualified name then only declared class of this package will be accessible.
Now there is no need to import. But you need to use fully qualified name every time when
you are accessing the class or interface.
It is generally used when two packages have same class name e.g. java.util and java.sql
packages contain Date class.
Example of package by import fully qualified name
//save by A.java
package pack;
public class A{
public void msg(){
System.out.println("Hello");
}
}
//save by B.java
package mypack;
class B{
public static void main(String args[]){
pack.A obj = new pack.A();//using fully qualified name
obj.msg();
}
}
Output:Hello
If you import a package, all the classes and interface of that package will be imported
excluding the classes and interfaces of the subpackages. Hence, you need to import the
subpackage as well.
Subpackage in java
Package inside the package is called the subpackage. It should be created to categorize the
package further.
Let's take an example, Sun Microsystem has defined a package named java that contains
many classes like System, String, Reader, Writer, Socket etc. These classes represent a
particular group e.g. Reader and Writer classes are for Input/Output operation, Socket and
ServerSocket classes are for networking etc and so on. So, Sun has subcategorized the java
package into subpackages such as lang, net, io etc. and put the Input/Output related classes
in io package, Server and ServerSocket classes in net packages and so on.
8. Interfaces
An interface in java is a blueprint of a class. It has static constants and abstract methods
only.
The interface in java is a mechanism to achieve fully abstraction. There can be only abstract
methods in the java interface not method body. It is used to achieve fully abstraction and
multiple inheritance in Java.
Java Interface also represents IS-A relationship.
It cannot be instantiated just like abstract class.
Why use Java interface?
There are mainly three reasons to use interface. They are given below.
It is used to achieve fully abstraction.
By interface, we can support the functionality of multiple inheritance.
It can be used to achieve loose coupling.
The java compiler adds public and abstract keywords before the interface method and
public, static and final keywords before data members.
In other words, Interface fields are public, static and final by default, and methods are public
and abstract.
As shown in the figure given below, a class extends another class, an interface extends
another interface but a class implements an interface.
Class extends class
Class implements interface
Interface extends interface
Simple example of Java interface
In this example, Printable interface have only one method, its implementation is provided
in the A class.
interface printable{
void print();
}
class A6 implements printable{
public void print(){System.out.println("Hello");}
public static void main(String args[]){
A6 obj = new A6();
obj.print();
}
}
Output:Hello
Multiple inheritance in Java by interface
If a class implements multiple interfaces, or an interface extends multiple interfaces i.e.
known as multiple inheritance.
interface Printable{
void print();
}
interface Showable{
void show();
}
class A7 implements Printable,Showable{
public void print(){
System.out.println("Hello");
}
public void show(){
System.out.println("Welcome");
}
public static void main(String args[]){
A7 obj = new A7();
obj.print();
obj.show();
}
}
Output: Hello
Welcome
Interface inheritance
A class implements interface but one interface extends another interface.
interface Printable{
void print();
}
interface Showable extends Printable{
void show();
}
class Testinterface2 implements Showable{
public void print(){
System.out.println("Hello");
}
public void show(){
System.out.println("Welcome");
}
public static void main(String args[]){
Testinterface2 obj = new Testinterface2();
obj.print();
obj.show();
}
}
Output:
Hello
Welcome
What is marker or tagged interface?
An interface that have no member is known as marker or tagged interface. For example:
Serializable, Cloneable, Remote etc. They are used to provide some essential information
to the JVM so that JVM may perform some useful operation.
//How Serializable interface is written?
public interface Serializable{
}
Difference between abstract class and interface
Abstract class and interface both are used to achieve abstraction where we can declare the
abstract methods. Abstract class and interface both can't be instantiated.
But there are many differences between abstract class and interface that are given below.
Abstract class Interface
1) Abstract class can have abstract Interface can have only abstract methods.
and non-abstract methods.
2) Abstract class doesn't support multiple Interface supports multiple inheritance.
inheritance.
3) Abstract class can have final, non-final, Interface has only static and final
static and non-static variables. variables.
4) Abstract class can have static methods, Interface can't have static methods, main
main method and constructor. method or constructor.
5) Abstract class can provide the Interface can't provide the implementation
implementation of interface. of abstract class.
6) The abstract keyword is used to declare The interface keyword is used to declare
abstract class. interface.
7) Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }
Java catch block is used to handle the Exception. It must be used after the try block only.
You can use multiple catch block with a single try.
Syntax:
....
try
{
statement 1;
statement 2;
try
{
statement 1;
statement 2;
}
catch(Exception e)
{
}
}
catch(Exception e)
{
}
Java nested try example
Let's see a simple example of java nested try block.
class Excep6{
public static void main(String args[]){
try{
try{
System.out.println("going to divide");
int b =39/0;
}catch(ArithmeticException e){System.out.println(e);
}
try{
int a[]=new int[5];
a[5]=4;
}catch(ArrayIndexOutOfBoundsException e){
System.out.println(e);
}
System.out.println("other statement);
}catch(Exception e){
System.out.println("handeled");
}
System.out.println("normal flow..");
}
}
....
Java finally block
Java finally block is a block that is used to execute important code such as closing connection,
stream etc.
Java finally block is always executed whether exception is handled or not.
Java finally block must be followed by try or catch block.
Why use java finally
o Finally block in java can be used to put "cleanup" code such as closing a
file, closing connection etc.
Usage of Java finally
Let's see the different cases where java finally block can be used.
Case 1
Let's see the java finally example where exception doesn't occur.
class TestFinallyBlock{
public static void main(String args[]){
try{
int data=25/5;
System.out.println(data);
}
catch(NullPointerException e){System.out.println(e);}
finally{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}
}
Output:5
finally block is always executed
rest of the code...
Case 2
Let's see the java finally example where exception occurs and not handled.
class TestFinallyBlock1{
public static void main(String args[]){
try{
int data=25/0;
System.out.println(data);
}
catch(NullPointerException e){System.out.println(e);}
finally{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}
}
Output: finally block is always executed
Exception in thread main java.lang.ArithmeticException:/ by zero
Case 3
Let's see the java finally example where exception occurs and handled.
public class TestFinallyBlock2{
public static void main(String args[]){
try{
int data=25/0;
System.out.println(data);
}
catch(ArithmeticException e){System.out.println(e);}
finally{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}
}
Output:Exception in thread main java.lang.ArithmeticException:/ by zero
finally block is always executed
rest of the code...
Rule 3: For each try block there can be zero or more catch blocks, but only one finally block.
Java throw exception
Java throw keyword
The Java throw keyword is used to explicitly throw an exception.
We can throw either checked or uncheked exception in java by throw keyword.
The throw keyword is mainly used to throw custom exception. We will see custom exceptions
later.
The syntax of java throw keyword is given below.
throw exception;
Let's see the example of throw IOException.
throw new IOException("sorry device error”);
//java throw keyword example
In this example, we have created the validate method that takes integer value as a parameter. If
the age is less than 18, we are throwing the ArithmeticException otherwise print a message
welcome to vote.
public class TestThrow1{
static void validate(int age){
if(age<18)
throw new ArithmeticException("not valid");
else
System.out.println("welcome to vote");
}
public static void main(String args[]){
validate(13);
System.out.println("rest of the code...");
}
}
Output:
Exception in thread main java.lang.ArithmeticException:not valid
Java throws keyword
The Java throws keyword is used to declare an exception. It gives an information to the
programmer that there may occur an exception so it is better for the programmer to provide the
exception handling code so that normal flow can be maintained.
Exception Handling is mainly used to handle the checked exceptions. If there occurs any
unchecked exception such as NullPointerException, it is programmers fault that he is not
performing checkup before the code being used.
Syntax of java throws
return_type method_name() throws exception_class_name{
//method code
}
Which exception should be declared?
Ans) checked exception only, because:
unchecked Exception: under your control so correct your code.
error: beyond your control e.g. you are unable to do anything if there occurs
VirtualMachineError or StackOverflowError.
Advantage of Java throws keyword
1. Checked Exception can be propagated (forwarded in call stack).
2. It provides information to the caller of the method about the exception.
Java throws example
Let's see the example of java throws clause which describes that checked exceptions can be
propagated by throws keyword.
import java.io.IOException;
class Testthrows1{
void m() throws IOException{
throw new IOException("device error"); //checked exception
}
void n() throws IOException{
m();
}
void p(){
try{
n();
}catch(Exception e){
System.out.println("exception handled");
}
}
public static void main(String args[]){
Testthrows1 obj=new Testthrows1();
obj.p();
System.out.println("normal flow...");
}
}
Output:
exception handled
normal flow...
There are two cases:
1. Case1: You caught the exception i.e. handle the exception using try/catch.
2. Case2: You declare the exception i.e. specifying throws with the method.
Case1: You handle the exception
In case you handle the exception, the code will be executed fine whether
exception occurs during the program or not.
import java.io.*;
class M{
void method()throws IOException{
throw new IOException("device error");
}
}
public class Testthrows2{
public static void main(String args[]){
try{
M m=new M();
m.method();
}catch(Exception e){System.out.println("exception handled");}
System.out.println("normal flow...");
}
}
Output:exception handled
normal flow...
Case2: You declare the exception
1. A) In case you declare the exception, if exception does not occur, the code will be
executed fine.
2. B) In case you declare the exception if exception occurs, an exception will be thrown
at runtime because throws does not handle the exception.
A) Program if exception does not occur
import java.io.*;
class M{
void method()throws IOException{
System.out.println("device operation performed");
}
}
class Testthrows3{
public static void main(String args[])throws IOException{ //declare exception
M m=new M();
m.method();
System.out.println("normal flow...");
}
}
Output: device operation performed
normal flow...
Example 2
1 //InitArray.java
2 // Initializing the elements of an array with an array initializer.
3 public class InitArray
4{
5 public static void main( String[] args )
6{
7 // initializer list specifies the value for each element
8 int[] array = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37 };
9 System.out.printf( "%s%8s\n", "Index", "Value" ); // column headings
10 // output each array element's value
11 for ( int counter = 0; counter < array.length; counter++ )
12 System.out.printf( "%5d%8d\n", counter, array[ counter ] );
13 } // end main
14 } // end class InitArray
Output:
Index Value
0 32
1 27
2 64
3 18
4 95
5 14
6 90
7 70
8 60
9 37
Fig. 6.2 | Two-dimensional array with three rows and four columns.
Two-Dimensional Arrays with Rows of Different Lengths:
int[][] b = { { 1, 2 }, { 3, 4, 5 } };
Creating Two-Dimensional Arrays with Array-Creation Expressions:
int[][] b = new int[ 3 ][ 4 ];
A multidimensional array in which each row has a different number of columns can be created
as follows:
int[][] b = new int[ 2 ][ ]; // create 2 rows
b[ 0 ] = new int[ 5 ]; // create 5 columns for row 0
b[ 1 ] = new int[ 3 ]; // create 3 columns for row 1
Two-Dimensional Array Example: Displaying Element Values
Example:
1 //InitArray.java
2 // Initializing two-dimensional arrays.
3 public class InitArray
4{
5 // create and output two-dimensional arrays
6 public static void main( String[] args )
7{
8 int[][] array1 = { { 1, 2, 3 }, { 4, 5, 6 } };
9 int[][] array2 = { { 1, 2 }, { 3 }, { 4, 5, 6 } };
10 System.out.println( "\nValues in array2 by row are" );
11 outputArray( array2 ); // displays array2 by row
12 } // end main
13 // output rows and columns of a two-dimensional array
14 public static void outputArray( )
15 {
16 System.out.println( "Values in array1 by row are" );
17 outputArray( array1 ); // displays array1 by row
18 System.out.println( "\nValues in array2 by row are" );
19 outputArray( array2 ); // displays array2 by row
20 } // end main
21 // output rows and columns of a two-dimensional array
22 public static void outputArray( )
21 {
31 } // end method outputArray
32 } // end class InitArray
Output:
Values in array1 by row are
123
456
Values in array2 by row are
12
3
456
7.0 INPUT/OUTPUT
The input/output class in Java allow us to make our programs more interactive by getting some
input from the user. The methods of getting input include the following:
1. Scanner class
i. Add this at the top of your code:
import java.util.Scanner;
ii. Add this statement:
Scanner st = new Scanner(System.in);
iii. Declare a temporary variable to get the input, and invoke the nextInt(),
nextDouble(), methods as the case may be to get input from the keyboard.
int a = st.nextInt();
2. BufferedReader class
i. Add this at the top of your code:
import java.io.*;
ii. Add this statement:
BufferedReader br = new BufferedReader(new InputStreamReader( System.in) );
iii. Declare a temporary String variable to get the input, and invoke the readLine()
method to get input from the keyboard. You have to type it inside a try-catch block.
try{
String temp = br.readLine();
}catch( IOException e ){
System.out.println(“Error in getting input”);
}
3. JOptionPane
Another way to get input from the user is by using the JOptionPane class which is found in
the javax.swing package. JOptionPane makes it easy to pop up a standard dialog box that
prompts users for a value or informs them of something.
Example:
import javax.swing.JOptionPane;
public class GetInputFromKeyboard
{
public static void main( String[] args ){
String name;
name = JOptionPane.showInputDialog("Please enter your name");
String msg = "Hello " + name + "!";
JOptionPane.showMessageDialog(null, msg);
}
}
This will output:
8.0 LABORATORY EXERCISES IN AN OOP LANGUAGE
1. Write a java program that can accept two matrices of any length of rows and columns
and perform arithmetic operations on them. The program should include a decision
menu that gives the user the chance to determine the number and type of arithmetic
operation (addition, subtraction and multiplication) to perform. [Hint: Use the switch
statement].
2. Write an application that reads array of integer numbers and perform different
operations on them. [Hint: addition, min, max, range, mode, median, mean, variance,
standard deviation, sorting, print even and odd numbers, etc.]
3. Define a Square class with the length of its side as an instance variable. Include an
appropriate constructor method and methods to enlarge an instance as well as compute
its area.
4. Using the Square class in Question 1, create ten randomly sized squares and find the
sum of their areas. (The method Math.random() returns a random number between 0.0
and 1.0 each time it is invoked).
5. Add the functionality for a Square object to draw itself via ASCII characters. For
example, a Square of length 4 can be drawn as:
****
* *
* *
****
Or:
XXXX
X++X
X++X
XXXX
The System.out.print() and System.out.println() methods may be useful.
6. Find a number with nine digits d1d2d3,…, d9 such that the sub-string number d1, …,
dn is divisible by n, 1<=n<=9. Note that each of the digits may be used once.
7. Design a simple calculator in Java using any relevant OOP features.
8. Write an application that reads five integers and determines and prints the largest and
smallest integers in the group. Use only the OOP techniques you learned in this course.
9. Write an application that reads two integers, determines whether the first is a multiple
of the second and prints the result. [Hint: Use the remainder operator.]
10. Explain why a class might provide a set method and a get method for an instance
variable.
11. Create a class called Employee that includes three instance variables—a first name
(type String), a last name (type String) and a monthly salary (double). Provide a
constructor that initializes the three instance variables. Provide a set and a get method
for each instance variable. If the monthly salary is not positive, do not set its value.
Write a test application named EmployeeTest that demonstrates class Employee’s
capabilities. Create two Employee objects and display each object’s yearly salary. Then
give each Employee a 10% raise and display each Employee’s yearly salary again.
12. Create a class called Date that includes three instance variables—a month (type int), a
day (type int) and a year (type int). Provide a constructor that initializes the three
instance variables and assumes that the values provided are correct. Provide a set and a
get method for each instance variable. Provide a method displayDate that displays the
month, day and year separated by forward slashes (/). Write a test application named
DateTest that demonstrates class Date’s capabilities.
13. Create a class called Invoice that a hardware store might use to represent an invoice for
an item sold at the store. An Invoice should include four pieces of information as
instance variables—a part number (type String), a part description (type String), a
quantity of the item being purchased (type int) and a price per item (double). Your class
should have a constructor that initializes the four instance variables. Provide a set and
a get method for each instance variable. In addition, provide a method named
getInvoiceAmount that calculates the invoice amount (i.e., multiplies the quantity by
the price per item), then returns the amount as a double value. If the quantity is not
positive, it should be set to 0. If the price per item is not positive, it should be set to 0.0.
Write a test application named InvoiceTest that demonstrates class Invoice’s
capabilities.
14. Explain what happens when a Java program attempts to divide one integer by another.
What happens to the fractional part of the calculation? How can you avoid that
outcome?
15. Develop a Java application that determines the gross pay for each of three employees.
The company pays straight time for the first 40 hours worked by each employee and
time and a half for all hours worked in excess of 40. You’re given a list of the
employees, their number of hours worked last week and their hourly rates. Your
program should input this information for each employee, then determine and display
the employee’s gross pay. Use class Scanner to input the data.
16. Write an application that prompts the user to enter the size of the side of a square, then
displays a hollow square of that size made of asterisks. Your program should work for
squares of all side lengths between 1 and 20.
17. A palindrome is a sequence of characters that reads the same backward as forward. For
example, each of the following five-digit integers is a palindrome: 12321, 55555, 45554
and 11611. Write an application that reads in a five-digit integer and determines
whether it’s a palindrome. If the number is not five digits long, display an error message
and allow the user to enter a new value.
18. Write an application that demonstrates drawing rectangles and ovals, using the
Graphics methods drawRect and drawOval, respectively. Your program graphical
interface should include option menu that require the user to input 1 to draw rectangles
and 2 to draw ovals.
19. A right triangle can have sides whose lengths are all integers. The set of three integer
values for the lengths of the sides of a right triangle is called a Pythagorean triple. The
lengths of the three sides must satisfy the relationship that the sum of the squares of two
of the sides is equal to the square of the hypotenuse. Write an application that displays
a table of the Pythagorean triples for side1, side2 and the hypotenuse, all no larger than
500. Use a triple-nested for loop that tries all possibilities. This method is an example
of “brute-force” computing. You’ll learn in more advanced computer science courses
that for many interesting problems there’s no known algorithmic approach other than
using sheer brute force.
20. Write a method isMultiple that determines, for a pair of integers, whether the second
integer is a multiple of the first. The method should take two integer arguments and
return true if the second is a multiple of the first and false otherwise. [Hint: Use the
remainder operator]. Incorporate this method into an application that inputs a series of
pairs of integers (one pair at a time) and determines whether the second value in each
pair is a multiple of the first.
21. Write a method isEven that uses the remainder operator (%) to determine whether an
integer is even. The method should take an integer argument and return true if the
integer is even and false otherwise. Incorporate this method into an application that
inputs a sequence of integers (one at a time) and determines whether each is even or
odd.
22. Use a one-dimensional array to solve the following problem: Write an application that
inputs five numbers, each between 10 and 100, inclusive. As each number is read,
display it only if it’s not a duplicate of a number already read. Provide for the “worst
case,” in which all five numbers are different. Use the smallest possible array to solve
this problem. Display the complete set of unique values input after the user enters each
new value.
23. Write an inheritance hierarchy for classes Quadrilateral, Trapezoid, Parallelogram,
Rectangle and Square. Use Quadrilateral as the superclass of the hierarchy. Create and
use a Point class to represent the points in each shape. Make the hierarchy as deep (i.e.,
as many levels) as possible. Specify the instance variables and methods for each class.
The private instance variables of Quadrilateral should be the x-y coordinate pairs for
the four endpoints of the Quadrilateral. Write a program that instantiates objects of your
classes and outputs each object’s area (except Quadrilateral).