0% found this document useful (0 votes)
144 views

Oop Notes

The document provides an overview of object-oriented programming concepts in Java including classes, objects, constructors, abstraction, encapsulation, inheritance, polymorphism, interfaces, wrapper classes, exceptions, input/output streaming, object serialization, Java collections, for-each loops, and GUI programming in Java using AWT and Swing. It includes code examples and definitions of key terms. The document is a handout for an object-oriented programming course using Java that covers fundamental OOP concepts.

Uploaded by

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

Oop Notes

The document provides an overview of object-oriented programming concepts in Java including classes, objects, constructors, abstraction, encapsulation, inheritance, polymorphism, interfaces, wrapper classes, exceptions, input/output streaming, object serialization, Java collections, for-each loops, and GUI programming in Java using AWT and Swing. It includes code examples and definitions of key terms. The document is a handout for an object-oriented programming course using Java that covers fundamental OOP concepts.

Uploaded by

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

Prof.

Uzair Salman Object Oriented Programming Using JAVA

Object Oriented Programming Using JAVA


Handouts

Table of Contents
Table of Contents ....................................................................................................................... 1
Object & Classes......................................................................................................................... 3
Constructor ................................................................................................................................ 4
Abstraction ................................................................................................................................. 4
Concrete classes ..................................................................................................................... 5
Encapsulation ............................................................................................................................. 5
Inheritance ................................................................................................................................. 6
IS-A Relationship (composition): ............................................................................................ 6
HAS-A Relationship:................................................................................................................ 7
Single Inheritance ........................................................................................................ 7
Multiple Inheritance .................................................................................................... 8
Multilevel Inheritance ................................................................................................. 8
Hierarchical Inheritance .............................................................................................. 9
Hybrid inheritance ....................................................................................................... 9
Up-casting & Down-casting .................................................................................................. 10
Up-casting: ........................................................................................................................ 10
Down-casting: ................................................................................................................... 10
Polymorphism .......................................................................................................................... 11
Method Overloading ............................................................................................................ 11
Method Overriding ............................................................................................................... 12
Interfaces ................................................................................................................................. 12
Wrapper Classes, Boxing & Unboxing, Packages ..................................................................... 14
Wrapper Classes............................................................................................................ 14
Boxing & Unboxing........................................................................................................ 14
Packages ........................................................................................................................ 14

Superior Group of Collage Jauharabad 1|Page


Prof. Uzair Salman Object Oriented Programming Using JAVA

Exceptions ................................................................................................................................ 15
Input/Output Streaming .......................................................................................................... 16
Reading Text File ........................................................................................................... 16
Writing to Text File........................................................................................................ 17
Object Serialization .................................................................................................................. 18
I. Serializing an Object........................................................................................................... 18
I. Deserializing an Object ....................................................................................................... 19
Java Collection ......................................................................................................................... 19
For-each loop ........................................................................................................................... 20
GUI in JAVA .............................................................................................................................. 21
Java AWT ....................................................................................................................... 21
JAVA Swing .................................................................................................................... 21
Some important Programs from past papers .......................................................................... 22
Short Answers & there Questions ........................................................................................... 32

Superior Group of Collage Jauharabad 2|Page


Prof. Uzair Salman Object Oriented Programming Using JAVA

Object & Classes


A class is a blueprint or template or set of instructions to build a specific type of object. Every
object is built from a class. Each class should be designed and programmed to accomplish
some tasks.

The term ‘object’, however, refers to an actual instance of a class. Every object must belong
to a class. Objects are created and eventually destroyed – so they only live in the program for
a limited time.
Or
Object - Objects have states and behaviors. Example: A CAR has states - color, model, speed
as well as behaviors –accelerate, break. An object is an instance of a class.

Class - A class can be defined as a template/blue print that describes the behaviors/states
that object of its type support.

Following Example illustrate class and object declaration:


public class student {
String name; //Data Members
int age; //Data Members

public void setData(String n, int a) //Member Functions


{
name = n;
age = a;
}
public void getData() //Member Functions
{
System.out.println("Name s :"+name);
System.out.println("age is :"+age);
}

public static void main (String[] arrgs) // Main function


{
student obj=new student(); // Object Creation
obj.setData("abc", 10); // Method Calling using object
obj.getData(); // Method Calling using object
}

Superior Group of Collage Jauharabad 3|Page


Prof. Uzair Salman Object Oriented Programming Using JAVA

Constructor
Constructor is a function in any class that is used to initialize data variables. Every class has a
constructor. If we do not explicitly write a constructor for a class the Java compiler builds a
default constructor for that class. Each time a new object is created, at least one constructor
will be invoked. The main rule of constructors is that they should have the same name as the
class and have no return type. A class can have more than one constructor.

Example:
public class student {
String name;
int age;

public student() //constructor


{
name="abc";
age=0;
}

public void show()


{
System.out.println("Name s :"+name);
System.out.println("age is :"+age);
}

public static void main (String[] arrgs)


{
student obj=new student(); // constructor automatically calls
obj.show();
}

Abstraction
Abstraction is a process of hiding the implementation details from the user, only the
functionality will be provided to the user. An abstract class is one that cannot be instantiated.
All their 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. In Java
Abstraction is achieved using Abstract classes, and Interfaces.

Example:

Superior Group of Collage Jauharabad 4|Page


Prof. Uzair Salman Object Oriented Programming Using JAVA

public abstract class student { // making class abstract using abstract keyword
String name;
int age;

public void setData(String n, int a)


{
name= n;
age= a;
}

public void getData()


{
System.out.println("Name s :"+name);
System.out.println("age is :"+age);
}

public static void main (String[] arrgs)


{
student obj=new student(); /* Following is not allowed and raise error */
obj.show();
}

Concrete classes
A concrete class in Java is any such class which has implementation of all of its inherited
members either from interface or abstract class
public abstract class A {
public abstract void methodA();
}

interface B {
public void printB();
}

public class C extends A implements B {


public void methodA() {
System.out.print("I am abstract implementation");
}

public void printB() {


System.out.print("I am interface implementation");
}
}}

Encapsulation
Encapsulation in Java is a mechanism of wrapping the data (variables) and code acting on the
data (methods) together as single unit. In encapsulation the variables of a class will be hidden
from other classes, No outside class can access private data member (variable) of other class.
However if we setup public getter and setter methods to update and read the private data

Superior Group of Collage Jauharabad 5|Page


Prof. Uzair Salman Object Oriented Programming Using JAVA

fields then the outside class can access those private data fields via public methods. This way
data can only be accessed by public methods thus making the private fields and their
implementation hidden for outside classes. That’s why encapsulation is known as data hiding.
Example:
public class student {
private String name; //Private Data Members
private int age; //private Data Members

public student() //constructor


{
name="abc";
age=0;
}
public void setData(String n, int a) //Member Functions
{
name = n;
age = a;
}
public void getData() //Member Functions
{
System.out.println("Name s :"+name);
System.out.println("age is :"+age);
}

public static void main (String[] arrgs) // Main function


{
student obj=new student(); // Object Declaration
obj.setData("abc", 10); // Method Calling using object
obj.getData(); // Method Calling using object
}

Inheritance
Inheritance can be defined as the process where one class acquires the properties (methods
and fields) of another. With the use of inheritance, the information is made manageable in a
hierarchical order. In other words, the derived class inherits the states and behaviors from
the base class. The derived class is also called subclass and the base class is also known as
super-class. The derived class can add its own additional variables and methods. These
additional variable and methods differentiates the derived class from the base class.

When we talk about inheritance, the most commonly used keyword would be extends and
implements. The superclass and subclass have “is-a” relationship between them.

IS-A Relationship (composition):


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.

Superior Group of Collage Jauharabad 6|Page


Prof. Uzair Salman Object Oriented Programming Using JAVA

public class Animal{


}
public class Mammal extends Animal{
}
public class Reptile extends Animal{
}
public class Dog extends Mammal{
}

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

HAS-A Relationship:
Composition (HAS-A) simply mean use of instance variables that are references to other
objects. For example: Honda has Engine, or House has Bathroom.

CAR
IS-A

Honda HAS-A Engine

Types of inheritance in Java:


Below are various types of inheritance in Java.
 Single Inheritance
Single inheritance is damn easy to understand. When a class extends another one
class only then we call it a single inheritance. The below flow diagram shows that class
B extends only one class which is A. Here A is a parent class of B and B would be a child
class of A.

Superior Group of Collage Jauharabad 7|Page


Prof. Uzair Salman Object Oriented Programming Using JAVA

Example:
public class A
{
public void methodA()
{
System.out.println("Base class method");
}
}

public class B extends A


{
public void methodB()
{
System.out.println("Child class method");
}
public static void main(String args[])
{
B obj = new B();
obj.methodA(); //calling super class method
obj.methodB(); //calling local method
}
}

 Multiple Inheritance
Multiple Inheritance” refers to the concept of one class extending (Or inherits) more
than one base class. Multiple Inheritance is very rarely used in software projects. Using
multiple inheritance often leads to problems in the hierarchy. Most of the new OOP
languages like Small Talk, Java, C# do not support Multiple inheritance. Multiple
Inheritance is supported in C++.

 Multilevel Inheritance
Multilevel inheritance refers to a mechanism in OOP where one can inherit from a
derived class, thereby making this derived class the base class for the new class. As you
can see in below flow diagram C is subclass or child class of B and B is a child class of A.

Example:

Superior Group of Collage Jauharabad 8|Page


Prof. Uzair Salman Object Oriented Programming Using JAVA

class A
{
public void methodA()
{
System.out.println("Class A method");
}
}
class B extends A
{
public void methodB()
{
System.out.println("class B method");
}
}
class C extends B
{
public void methodC()
{
System.out.println("class C method");
}
public static void main(String arrgs[])
{
C obj = new C();
obj.methodA(); //calling grand parent class method
obj.methodB(); //calling parent class method
obj.methodC(); //calling local method
}
}

 Hierarchical Inheritance
In such kind of inheritance one class is inherited by many sub classes. In below
example class B,C and D inherits the same class A.

 Hybrid inheritance
Hybrid inheritance is a combination of Single and Multiple inheritance. A hybrid
inheritance can be achieved in the java in a same way as multiple inheritance can be!!
Using interfaces. By using interfaces you can have multiple as well as hybrid
inheritance in Java.

Superior Group of Collage Jauharabad 9|Page


Prof. Uzair Salman Object Oriented Programming Using JAVA

Up-casting & Down-casting


Casting in java means converting from type to type. When it comes to the talking about up-
casting and down-casting concepts we are talking about converting the objects references
types between the child type classes and parent type class. Suppose that we have three
classes (A, B, C). Class B inherit from class A. Class C inherit from class B. As follows

class A
{
void display(){}
}
class B implements A
{
public void display() {
System.out.println("Am in class B");
}

}
class C extends B
{
public void display() {
System.out.println("Am in class C");
}
}

Up-casting:
The up casting is casting from the child class to base class. The up casting in java is implicit
which means that you don't have to put the braces (type) as an indication for casting. Below
is an example of up casting where we create a new instance from class C and pass it to a
reference of type A. Then we call the function display.

public static void main (String[] arrgs) // Main function


{
A obj=new C(); // up-casting from subclass to super class
obj.display(); // Method Calling of class C
}

Down-casting:
The up casting is casting from the base class to child class. The down-casting in java is explicit
which means that you have to put the braces (type) as an indication for casting. Below is an
example of down-casting
public static void main (String[] arrgs) // Main function
{
A obj=new C(); // upcasting from subclass to
super class
obj.display(); // Method Calling of class C
B objB=(B) obj; //Downcasting of reference to
subclass reference
objB.display(); //method calling of class C
}

Superior Group of Collage Jauharabad 10 | P a g e


Prof. Uzair Salman Object Oriented Programming Using JAVA

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.
Example
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 examples −

 A Deer IS-A Animal


 A Deer IS-A Vegetarian
 A Deer IS-A Deer
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;
All the reference variables d, a, v refer to the same Deer object

Method Overloading
If a class has multiple methods having same name but different in parameters, it is known as
Method Overloading. If we have to perform only one operation, having same name of the
methods increases the readability of the program.
Suppose you have to perform addition of the given numbers but there can be any number of
arguments, if you write the method such as A(int,int) for two parameters, and B(int,int,int)
for three parameters then it may be difficult for you as well as other programmers to
understand the behavior of the method because its name differs. So, we perform method
overloading to figure out the program quickly.
There are two ways to overload the method in java

 By changing number of arguments


 By changing the data type
We can solve the given addition function problem using function overloading as:

Superior Group of Collage Jauharabad 11 | P a g e


Prof. Uzair Salman Object Oriented Programming Using JAVA

class Adder{
int add(int a,int b){return a+b;}
int add(int a,int b,int c){return a+b+c;}
}
class mainClass{
public static void main(String args[]){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}}

Method Overriding
If subclass (child class) has the same method as declared in the parent class, it is known as
method overriding in java. In other words, If subclass provides the specific implementation
of the method that has been provided by one of its parent class, it is known as method
overriding. Method overriding is used to provide specific implementation of a method that is
already provided by its super class .It is used for runtime polymorphism.
Rules for Java Method Overriding

 method must have same name as in the parent class


 method must have same parameter as in the parent class.
 must be IS-A relationship (inheritance).
Example:
1. class Vehicle{
2. void run(){System.out.println("Vehicle is running");}
3. }
4. class Bike extends Vehicle{
5. void run(){System.out.println("Bike is running safely");}
6. }
7. Class mainClass{
8. public static void main(String args[]){
9. Bike2 obj = new Bike2();
obj.run();
}
}

Interfaces
Interface looks like class but it is not a class. An interface can have methods and variables just
like the class but the methods declared in interface are by default abstract (only method
signature, no body). Also, the variables declared in an interface are public, static & final by
default. We cannot instantiate an interface. Also an interface does not have any constructor.

Superior Group of Collage Jauharabad 12 | P a g e


Prof. Uzair Salman Object Oriented Programming Using JAVA

Since methods in interfaces are abstract and do not have body, they have to be implemented
by the class before you can access them. The class that implements interface must implement
all the methods of that interface. Also, java programming language does not support multiple
inheritances, using interfaces we can achieve this as a class can implement more than one
interfaces.
Key Points:
 We can’t instantiate an interface in java.
 Interface provides complete abstraction as none of its methods can have body.
 Implements keyword is used by classes to implement an interface.
 Any interface can extend any other interface but cannot implement it. Class
implements interface and interface extends interface.
 A class can implement any number of interfaces.
 An interface is written in a file with a .java extension, with the name of the interface
matching the name of the file.
 The interface keyword is used to declare an interface.
Example:
interface vehicle
{
/* All of the methods are abstract by default */
public void accelerate();
public void breaking();
}

class CAR implements vehicle


{

public void accelerate() {

System.out.println("Car is accelerating");

public void breaking() {


System.out.println("Break applied");
}

public static void main(String[] arrgs)


{
CAR obj=new CAR(); //object of Class CAR
obj.accelerate();
obj.breaking();
}
}

Superior Group of Collage Jauharabad 13 | P a g e


Prof. Uzair Salman Object Oriented Programming Using JAVA

Wrapper Classes, Boxing & Unboxing, Packages

 Wrapper Classes
Each of Java's eight primitive data types (int, byte, shot, long, float, double, Boolean, char) has
a class dedicated to it. These are known as wrapper classes, because they "wrap" the primitive
data type into an object of that class. So there is an Integer class that holds an int variable,
there is a Double class that holds a double variable, and so on. The wrapper classes are part
of the java.lang package, which is imported by default into all Java programs.
The following two statements illustrate the difference between a primitive data type and an
object of a wrapper class:

int x = 25;
Integer y = new Integer(33);

The first statement declares an int variable named x and initializes it with the value 25. The
second statement instantiates an Integer object. The object is initialized with the value 33
and a reference to the object is assigned to the object variable y.

 Boxing & Unboxing


o Conversion of a primitive type to the corresponding reference type is called boxing,
such as an int to a java.lang.Integer.
o Conversion of the reference type to the corresponding primitive type is called
unboxing, such as Byte to byte.
 Packages
Packages are used in Java in order to prevent naming conflicts, to control access, to make
searching/locating and usage of classes, interfaces, enumerations and annotations easier,
etc. A Package can be defined as a grouping of related types (classes, interfaces,
enumerations and annotations) providing access protection and name space management.
Some of the existing packages in Java are::
o java.lang - bundles the fundamental classes
o java.io - classes for input , output functions are bundled in this package
Programmers can define their own packages to bundle group of Classes/interfaces, etc.

Superior Group of Collage Jauharabad 14 | P a g e


Prof. Uzair Salman Object Oriented Programming Using JAVA

Exceptions
An exception (or exceptional event) is a problem that arises during the execution of a
program. When an Exception occurs the normal flow of the program is disrupted and the
program terminates abnormally, therefore these exceptions are to be handled. An exception
can occur for many different reasons, below given are some scenarios where exception
occurs.
o A user has entered invalid data.
o A file that needs to be opened cannot be found.
A method catches an exception using a combination of the try and catch keywords. A
try/catch block is placed around the code that might generate an exception. The syntax for
using try/catch looks like the following:
try{
//Do something
}
catch(Exception ex)
{
//Catch exception hare using exception argument ex
}

The code which is prone to exceptions is placed in the try block, when an exception occurs,
that exception occurred is handled by catch block associated with it.
Example:

public class ExceptionSample {

public static void main (String[] arrgs) // Main function


{
int no1, no2; //Data variables
no1=5; //Contain some value
no2=0; //contain some value

try // Try block


{
System.out.println(no1/no2); //attempt to divide number
by 0
}
catch (Exception ex) // Catch block receive exception
{
/* Display exception message */
System.out.println("Error with defination:
"+ex.getMessage()); }
}
}

Superior Group of Collage Jauharabad 15 | P a g e


Prof. Uzair Salman Object Oriented Programming Using JAVA

Input/Output Streaming
The java.io package contains nearly every class you might ever need to perform input and
output (I/O) in Java. All these streams represent an input source and an output destination.
A stream can represent many different kinds of sources and destinations, including disk files,
devices, other programs, and memory arrays. Streams support many different kinds of data,
including simple bytes, primitive data types, localized characters, and objects. Some streams
simply pass on data; others manipulate and transform the data in useful ways.

1: Reading information into program using StreamRead er

2: Writing information from program using StreamWriter

You can read files using these classes:

• FileReader for text files in your system's default encoding (for example, files
containing Western European characters on a Western European computer).

• FileInputStream for binary files and text files that contain 'weird' characters

FileReader (for text files) should usually be wrapped in a BufferedFileReader. This saves up
data so you can deal with it a line at a time or whatever instead of character by character. If
you want to write files, basically all the same stuff applies, except you'll deal with classes
named FileWriter with BufferedFileWriter for text files, or FileOutputStream for binary files.

 Reading Text File


If you want to read an ordinary text file in your system's default encoding, use FileReader and
wrap it in a BufferedReader. In the following program, we read a file called "myFile.txt" and
output the file line by line on the console.
import java.io.*;

Superior Group of Collage Jauharabad 16 | P a g e


Prof. Uzair Salman Object Oriented Programming Using JAVA

public class fileHandling {

String textFile;
String line;

public void ReadTextFile(String FileName)


{
textFile = FileName;
try {
FileReader Reader = new FileReader(textFile);
BufferedReader bufferedReader = new BufferedReader(Reader);

while((line = bufferedReader.readLine()) != null) {


System.out.println(line);
}

bufferedReader.close(); // close files.


}
catch(Exception ex) {
System.out.println("Error Reading File");
}
}
public static void main (String[] arrgs)
{
fileHandling obj=new fileHandling();

obj.ReadTextFile("c:\\MyFile.txt");
}
}

 Writing to Text File


To write a text file in Java, use FileWriter instead of FileReader, and
BufferedOutputWriter instead of BufferedOutputReader. Here's an example program
that creates a file called 'temp.txt' and writes some lines of text to it.
import java.io.*;
public class fileHandling {

String textFile;
public void WriteFile(String File)
{
textFile = File;
try {
FileWriter Writer = new FileWriter(textFile);

BufferedWriter bufferedWriter =new BufferedWriter(Writer);

bufferedWriter.write("Hello there,");
bufferedWriter.newLine();
bufferedWriter.write("We are writing");
bufferedWriter.close(); // Always close files.
}
catch(Exception ex) {
System.out.println("Error writing to file");

Superior Group of Collage Jauharabad 17 | P a g e


Prof. Uzair Salman Object Oriented Programming Using JAVA

}
}

public static void main (String[] arrgs)


{
fileHandling obj=new fileHandling();

obj.WriteFile("c:\\MyFile.txt");
}
}

Object Serialization
Java provides a mechanism, called object serialization where an object can be represented as
a sequence of bytes that includes the object's data as well as information about the object's
type and the types of data stored in the object.
After a serialized object has been written into a file, it can be read from the file and
deserialized that is, the type information and bytes that represent the object and its data can
be used to recreate the object in memory.
Most impressive is that an object can be serialized on one platform and deserialized on an
entirely different platform.
Classes ObjectInputStream and ObjectOutputStream are high-level streams that contain the
methods for serializing and deserializing an object.

Notice that for a class to be serialized successfully, two conditions must be met −

 `The class must implement the java.io.Serializable interface.


 All of the fields in the class must be serializable.

I. Serializing an Object
The ObjectOutputStream class is used to serialize an Object.

import java.io.*;
public class Serialize{

public static void main(String [] args) {


Employee e = new Employee(); // instance of class
employee
e.name = " Ali Ahmad"; // initialization of
members
e.address = "New satellite town , jauharabad";
e.number = 101;

try {
FileOutputStream fileOut =
new FileOutputStream("/tmp/employee.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);

Superior Group of Collage Jauharabad 18 | P a g e


Prof. Uzair Salman Object Oriented Programming Using JAVA

out.writeObject(e);
out.close();
fileOut.close();
System.out.printf("Serialized data is saved in /tmp/employee.ser");
} catch (IOException i) {
System.out.printf("Error writing object");
}
}
}

I. Deserializing an Object
The ObjectInputStream class is used to deserialize an Object.
import java.io.*;
public class Deserialize {

public static void main(String [] args) {


Employee e = null;
try {
FileInputStream fileIn = new FileInputStream("/tmp/employee.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
e = (Employee) in.readObject();
in.close();
fileIn.close();
} catch (IOException i) {
System.out.printf("Error writing object");
return;
}
System.out.println("Name: " + e.name);
System.out.println("Address: " + e.address);
System.out.println("Number: " + e.number);
}
}

Java Collection
Collections in java is a framework that provides an architecture to store and manipulate
the group of objects. All the operations that you perform on a data such as searching,
sorting, insertion, manipulation, deletion etc. can be performed by Java Collections.

Java Collection simply means a single unit of objects. Java Collection framework provides
many interfaces (Set, List, Queue, Deque etc.) and classes (ArrayList, Vector, LinkedList,
PriorityQueue, HashSet, LinkedHashSet, TreeSet etc).

Superior Group of Collage Jauharabad 19 | P a g e


Prof. Uzair Salman Object Oriented Programming Using JAVA

For-each loop
A new way of iteration was introduced in Java 5 and offers a more convenient way of
iterating over arrays and collections. It is an extension to the classic for loop and it is widely
known as “enhanced for” or “for-each”. The main difference between the classic for loop
and the new loop is the fact that it hides the iteration variable. As a result, usage of the
for-each loop leads to a more readable code with one less variable to consider each time
we want to create a loop thus the possibility of ending up with a logic error is smaller.

We can use it over both arrays and collections.

Example:
public static void main (String[] arrgs)
{

ArrayList arr=new ArrayList();


arr.add("A");
arr.add("B");
arr.add("C");
arr.add("D");
arr.add("E");
//Using foreach over collection
for (Object s : arr) {
System.out.println(s);
}

Superior Group of Collage Jauharabad 20 | P a g e


Prof. Uzair Salman Object Oriented Programming Using JAVA

GUI in JAVA
There are two sets of Java APIs for graphics programming: AWT (Abstract Windowing Toolkit) and
Swing.

I. AWT : Most of the AWT components have become obsolete and should be replaced by newer
Swing components.
II. Swing API: a much more comprehensive set of graphics libraries that enhances the AWT.

 Java AWT

AWT is huge! It consists of 12 packages of 370 classes. Java AWT components are platform-
dependent i.e. components are displayed according to the view of operating system. AWT is
heavyweight i.e. its components are using the resources of OS.

The java.awt package provides classes for AWT api such as TextField, Label, TextArea,
RadioButton, CheckBox, Choice, List etc.

 JAVA Swing

Java Swing is a part of Java Foundation


Classes (JFC) that is used to create
window-based applications. It is built on
the top of AWT (Abstract Windowing
Toolkit) API and entirely written in java.

The javax.swing package provides classes


for java swing API such as JButton,
JTextField, JTextArea, JRadioButton,
JCheckbox, JMenu, JColorChooser etc.

Java AWT Hierarchy

Superior Group of Collage Jauharabad 21 | P a g e


Prof. Uzair Salman Object Oriented Programming Using JAVA

Some important Programs from past papers


1. Write a program that has three fields hours, minute, second. To initialize these
fields, it has constructor getter and setter methods, and a print time method to
display time. Also override toString method in this class.
public class TimeClass{

private int hour;


private int minute;
private int second;

public TimeClass()
{
hour = minute = second = 0;
}

public void setter(int h, int m, int s)


{
if ( ( h >= 0 && h < 24 ) && ( m >= 0 && m < 60 ) && ( s >= 0 && s < 60 ) )
{
hour = h;
minute = m;
second = s;
}

Superior Group of Collage Jauharabad 22 | P a g e


Prof. Uzair Salman Object Oriented Programming Using JAVA

}
public int getHour() {
return hour;
}

public int getMinute() {


return minute;
}

public int getSecond() {


return second;
}

public String toString()


{
return String.format( "%d:%02d:%02d %s",
( ( hour == 0 || hour == 12 ) ? 12 : hour % 12 ),
minute, second, ( hour < 12 ? "AM" : "PM" ) );
} // end method toString

public static void main(String arrgs[])


{
TimeClass obj=new TimeClass();
obj.setter(12, 36, 25); // set time to 12:36:25
System.out.println(obj.toString()); // output: 12:36:25 PM
}

2. Create a class called Date that include three instance variable a Day(int) Month(int)
year(int). Provide a constructor to initialize these variables. Write getter and setter
methods and a method displayDate that display month, day and year separated by
(/) . create a demo application that demonstrate capability of Date class
public class Date
{
private int day,month,year;

public Date()
{
day=01;
month=01;
year=2001;
}
// public getter methods
public int getDay()
{ return day; }
public int getMonth()
{ return month; }
public int getYear()
{ return year; }

// public Setter methods


public void setDate(int d,int m, int y)
{
day=d;

Superior Group of Collage Jauharabad 23 | P a g e


Prof. Uzair Salman Object Oriented Programming Using JAVA

month=m;
year=y;
}

public void displayDate()


{
System.out.println(month+"/"+day+"/"+year);
}
}
public class demoApp {

public static void main(String args[])


{
Date obj=new Date();
obj.setDate(24, 12, 2017); // setDate function called
obj.displayDate(); // display date in mm/dd/yy formate

}
}

3. Create a distance class with instance variable feet and inches . write suitable
parameterized constructor, getter and setter methods and a method that add two
distance objects in such a way if inches exceed to 12 it will increment feet using this
statement dist3.add(dist1,dist2).
class distance{
double inch;
double feet;

public distance(double i, double f)


{
inch=i;
feet=f;
}

public double getFeet()


{
return feet;
}
public double getInch()
{
return inch;
}

public void showDist()


{
System.out.println("Feet: "+ feet + "\tInches: "+ inch);
}

public void setter(double f, double i)


{
inch=i;
feet=f;
}

Superior Group of Collage Jauharabad 24 | P a g e


Prof. Uzair Salman Object Oriented Programming Using JAVA

public void add(distance dist1, distance dist2) {


inch=dist1.inch+dist2.inch;
feet=dist1.feet+dist2.feet+(inch/12);
inch=inch%12;
}

}
public class MainClass {

public static void main(String args[])


{
distance dist1=new distance(10, 20);
distance dist2=new distance(10, 20);
distance dist3=new distance(0, 0);

dist3.add(dist1, dist2);
dist3.showDist();

4. Write a java program that has two classes point and circle. Circle class extends point
class. Demonstration up casting by using circle class.
class point
{
public void display() {
System.out.println("method of class point");
}

}
class Circle extends point
{
public void display() {
System.out.println("method of class circle");
}
public static void main (String arrgs[])
{
point obj=new Circle(); // up-casting from subclass to
super class
obj.display(); // Method Calling of class circle
}
}

5. Write a Bird class that has talk method. Define Crow, Owl and Parrot classes that
extend Bird class and override talk method. Demonstrate polymorphism using these
classes.
public abstract class Bird {
public void Talk();
}

public class Crow extends Bird {

Superior Group of Collage Jauharabad 25 | P a g e


Prof. Uzair Salman Object Oriented Programming Using JAVA

@Override
public void Talk() {
system.out.println(“Crow is talking”);
}
}

public class Owl extends Bird {


@Override
public void draw () {
system.out.println(“Owl is talking”);
}
}

public class Parrot extends Bird {


@Override
public void Talk () {
system.out.println(“Parrot is talking”);
}

public static void main(String args[]) {


Bird b1= new Crow();
B1.Talk(); // output: Crow is talking
Bird b1= new Owl();
B1.Talk(); // output: Owl is talking
Bird b1= new Parrot();
B1.Talk(); // output: Parrot is talking
}

6. Write a java program that has Shape class and sub classes Rectangle, Oval and
triangle. Use these classes to demonstrate polymorphism.
public abstract class Shape {
public abstract double area();
public abstract void draw();
}

public class Rectangle extends Shape {


private final double width, length; //sides

public Rectangle() {
width=1;
length=1;
}
@Override
public double area() {
return width * length;
}
@Override
public void draw() {
system.out.println(“Rectangle is drawn”);
}
}

public class Triangle extends Shape {


private final double a, b, c; // sides

Superior Group of Collage Jauharabad 26 | P a g e


Prof. Uzair Salman Object Oriented Programming Using JAVA

public Triangle() {
this(1,1,1);
}

@Override
public double area() {
double s = (a + b + c) / 2;
return Math.sqrt(s * (s - a) * (s - b) * (s - c));
}

@Override
public void draw () {
system.out.println(“Triangle is drawn”);
}
}

public class Oval extends Shape {


private final double a, b; // axis

public Oval() {
this(1,1);
}

@Override
public double area() {
return 3.14*a*b;
}

@Override
public void draw () {
system.out.println(“Oval is drawn”);
}
}

public class TestShape {


public static void main(String[] args) {

// Rectangle test
double width = 5, length = 7;
Shape rectangle = new Rectangle(width, length);
System.out.println("Rectangle area: " + rectangle.area());
rectangle.draw();

// Oval test
double a= 5, b= 4;
Shape Oval = new Oval(a, b);
System.out.println("Oval Area: " + Oval.area());
Oval.draw();

// Triangle test
double a = 5, b = 3, c = 4;
Shape triangle = new Triangle(a,b,c);
System.out.println("Triangle Area: " + triangle.area());
triangle.draw();
}
}

Superior Group of Collage Jauharabad 27 | P a g e


Prof. Uzair Salman Object Oriented Programming Using JAVA

7. What is exception handling in java? Write a java program to handle exceptions.

Ans: check Exceptions topic above in notes.

8. Write an application that throws an ArithematicException when you take square


root of a negative value.
import java.util.Scanner;

public class Sqrtclass {

public static void main(String args[]) {

Scanner sc = new Scanner(System.in); //for input


double i = 0;
System.out.println("Enter a number");
try{
i = sc.nextInt();
if(i<0)
throw new ArithmeticException ("negative number");

}
catch(ArithmeticException e){
System.out.println(e.getMessage());
}
System.out.println(Math.sqrt(i));
}
}
9. Explain the advantages of using interfaces in java? How they are different form
abstract classes. Support your answer with code example.

Ans: There are several advantages in utilizing the features of Interfaces in general
programming. Interfaces define a set of functionality as a rule or a contract. When we
implement an interface all of these functionality must be implemented in the inherited class.
In general, when one writes a simple program, one may not think about the need of using an
Interface. But when you are building a larger system or a library which keeps evolving, it is a
good idea to use Interface. A particular advantage of using interface in Java is that it allows
multiple inheritance.
(For example see detail section of interfaces and for difference check short answer section)

10. Use java text stream to read a text file “myfile1.txt” and copy contents of file to
another file “myfile2.txt”
class fileHandling {

String FileText;
String line;

public fileHandling()
{
FileText=null;
line=null;

Superior Group of Collage Jauharabad 28 | P a g e


Prof. Uzair Salman Object Oriented Programming Using JAVA

public String ReadFile(String FileName)


{
String Data=null;
try {
FileReader Reader = new FileReader(FileName);
BufferedReader bufferedReader = new BufferedReader(Reader);

while((line = bufferedReader.readLine()) != null) {


Data=Data+line;
}

bufferedReader.close(); // close files.


}
catch(Exception ex) {
System.out.println("Error Reading File");
}
return Data;
}

public void WriteFile(String File,String text)


{
try {
FileWriter Writer = new FileWriter(File);

BufferedWriter bufferedWriter =new BufferedWriter(Writer);

bufferedWriter.write(text);
bufferedWriter.newLine();
bufferedWriter.close(); // Always close files.
}
catch(Exception ex) {
System.out.println("Error writing to file");
}
}

public void copyFile(String inputFile, String outputFile)


{
FileText=ReadFile(inputFile);
WriteFile(outputFile, FileText);
}

public static void main (String[] arrgs)


{
fileHandling obj=new fileHandling();

obj.CopyFile("c:\\myfile1.txt","c:\\myfile2.txt");
}

11. Use java swing library to create a simple four function arithmetic calculator using
swing library.
import java.awt.*;
import javax.swing.*;
public class LoanCalc extends JFrame{

Superior Group of Collage Jauharabad 29 | P a g e


Prof. Uzair Salman Object Oriented Programming Using JAVA

private JButton btnCalc;


private JTextField number1;
private JTextField number2;
private JTextField op;
private JTextField result;
private JLabel lable1;
private JLabel lable2;
private JLabel lable3;
private JLabel lable4;
LoanCalc()
{
setTitle("Basic Calculator");
setBounds(200,200,400,500);
btnCalc=new JButton("Calculate");
number1=new JTextField();
number2=new JTextField();
op=new JTextField();
result=new JTextField();

lable1=new JLabel("First Number");


lable2=new JLabel("Second Number");
lable3=new JLabel("Operation");
lable4=new JLabel("Result");

setLayout(null);

number1.setBounds(120, 100, 200, 50);


number2.setBounds(120, 150, 200, 50);
op.setBounds(120, 200, 200, 50);
result.setBounds(120, 350, 200, 50);
lable1.setBounds(20,100, 100,50);
lable2.setBounds(20, 150, 100, 50);
lable3.setBounds(20, 200, 100, 50);
lable4.setBounds(20, 350, 100, 50);

btnCalc.setBounds(150, 280, 100, 50);

btnCalc.addActionListener(new listner());
btnCalc.setActionCommand("Calculate");
add(number1);
add(number2);
add(op);
add(result);
add(btnCalc);
add(lable1);
add(lable2);
add(lable3);
add(lable4);

public class listner implements ActionListener


{

@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub

Superior Group of Collage Jauharabad 30 | P a g e


Prof. Uzair Salman Object Oriented Programming Using JAVA

String btn=e.getActionCommand();
int no1,no2, ans=0;
String opration;
if(btn=="Calculate")
{
no1= Integer.parseInt(number1.getText());
no2= Integer.parseInt(number1.getText());
opration= op.getText();
switch (opration) {
case "+":
ans=no1+no2;
break;
case "-":
ans=no1-no2;
break;
case "*":
ans=no1*no2;
break;
case "/":
if(no2>0)
ans=no1/no2;
else
ans=0;
break;
default:
ans=0;
break;
}
result.setText(Integer.toString(ans));
}
}

}
}

Superior Group of Collage Jauharabad 31 | P a g e


Prof. Uzair Salman Object Oriented Programming Using JAVA

Short Answers & there Questions


1. What is object oriented programming?
Ans: Object-oriented programming (OOP) refers to a type of computer programming in which
programmers define not only the data type of a structure, but also the types of operations
(functions) that can be applied to the structure. In this way, the structure becomes an object
that includes both data and functions. In addition, programmers can create relationships
between one object and another.
2. Explain encapsulation in java?
Ans: Encapsulation in java is a process of wrapping code and data together into a single unit
(Hide it). We can assign access level of members of the class as private public and protected.
It provides you the control over the data.
3. What is abstract class?
Ans: Abstraction is a process of hiding the internal details and showing only important things
to the user. A class that is declared as abstract is known as abstract class. It needs to inherited.
We cannot create an object of abstract class. example sending SMS, you just type the text and
send the message. You don't know the internal processing about the message delivery.
4. What is constructor overloading in java?
Ans: Constructor overloading is a technique in which a class can
have more than one constructors with differ number of
parameter. The compiler differentiates these constructors by
number of parameters in the and their type.
5. What is final variable? Also write the syntax of declaration of final variable.
Ans: If we make any variable as final, you cannot change the value of final variable (It will be
constant). Syntax of declaring final variable is
final int speedlimit=80;//final variable

6. Describe wrapper classes.


Ans: Wrapper classes encapsulate primitive data types and related operations on it. It allows
primitive datatype to be accessed as objects. Boolean, Byte, Character, Double, Float, Integer,
Long and Short are example of wrapper classes. Wrapper classes make the primitive type data
to act as objects.
7. What is meaning of immutable in term of String?
Ans: string objects are immutable. Immutable simply means unmodifiable or unchangeable.
Once string object is created its data or state can't be changed but a new string object is
created. For example

Superior Group of Collage Jauharabad 32 | P a g e


Prof. Uzair Salman Object Oriented Programming Using JAVA

String name="UZAIR";
name.concat(" SALMAN");//concat() method appends the string at the end
System.out.println(s);//will print UZAIR because strings are immutable objects

Output:UZAIR

String constant
Pool
name
“UZAIR”

“UZAIR SALMAN”

8. What is method overriding?


Ans: Declaring a method in child class which is already present in parent class is known as
method overriding. Overriding is done so that a child class can give its own implementation
to a method which is already provided by the parent class. For example
class Human{
//Overridden method
public void eat()
{
System.out.println("Human is eating");
}
}
class Boy extends Human{
//Overriding method
public void eat(){
System.out.println("Boy is eating");
}

9. What is difference between checked and unchecked exception?


Ans: Checked exceptions are the exceptions which may occur regularly in a program and
compiler will check for those exceptions at “Compile Time”. Those exceptions are called
Checked Exceptions. Example: FileNotFoundException, EndOfFileException etc. exceptions
are handled with “Try&Catch” or “throws”.
Unchecked exceptions are some exceptions which do not occur regularly in a program, and
compiler will not check for those exceptions, these kind of exceptions are called Unchecked
Exceptions Example: ArithmeticException, NullPointerException etc.
10. What is difference between throw and throws?
Ans: throws clause is used to declare an exception and throw keyword is used to throw an
exception explicitly. The keyword throw is used inside method body to invoke an exception
and throws clause is used in method declaration (signature).
11. What is the purpose of super keyword?

Superior Group of Collage Jauharabad 33 | P a g e


Prof. Uzair Salman Object Oriented Programming Using JAVA

Ans: The super keyword in java is a reference variable which is used to refer parent class
object. Whenever you create the instance of child class, an instance of parent class is created
implicitly which is referred by super reference variable.
class vehicle {
public String color= "white";
}
class car extends vehicle {
public String color= "black";

public void print() {


System.out.println(color); //prints color of car class
System.out.println(super.color); //prints color of vehicle class
}
}

12. What is difference between String and StringBuilder classes ?


Ans: String object is immutable whereas StringBuilder objects are mutable. immutable mean
that the value stored in the String object cannot be changed. Where mutable means they can
change their values.
13. What is method overloading?

Ans: If a class has multiple methods having same name but different in parameters, it is known
as Method Overloading. if we have to perform only one operation, having same name of the
methods increases the readability of the program. Example

class Adder{
static int add(int a,int b){return a+b;}
static int add(int a,int b,int c){return a+b+c;}
}

14. What do you know about lang package in java?

Ans: Java.lang package contains the classes and interfaces that are fundamental to the design
of the Java programming language. the java.lang package is implicitly imported by every Java
source file. These classes includes : object , Thread, Throwable, Classes, Math, String etc.

15. Write the name of access specifiers in java.

Ans: Java provides a number of access


modifiers to set the level of access for
classes as well as the fields and methods.
These Access Modifiers are:

 private
 protected
 default
 public

Superior Group of Collage Jauharabad 34 | P a g e


Prof. Uzair Salman Object Oriented Programming Using JAVA

16. What is difference between interface and abstract classes?

Ans:

17. Why we use final keyword with? (class, method or variable)

Ans: final keyword is used in different contexts. When a variable is declared with final
keyword, it’s value can’t be modified, essentially, a constant. When a class is declared
with final keyword, it is called a final class. A final class cannot be extended(inherited).
When a method is declared with final keyword, it is called a final method. A final method
cannot be overridden.

18. Give a simple use of ArrayList class.

Ans: Java ArrayList class uses a dynamic array for storing the elements. We can declare an
ArrayList like this
ArrayList al=new ArrayList();//creating old non-generic arraylist
ArrayList<String> al=new ArrayList<String>();//creating new generic arraylist

19. How we can join two strings in java?

Ans: we can join two Java String fields using the + operator, for example
String firstName = "uzair";
String lastName = "salman";
String fullName = firstName + lastName;

20. What are two main component of class?

Ans: there are data members as well as member function within a class to define an object
characteristics.

Superior Group of Collage Jauharabad 35 | P a g e


Prof. Uzair Salman Object Oriented Programming Using JAVA

21. For what purpose ‘This’ keyword is used?

Ans: It(this) works as a reference to the current Object whose Method or constructor is being
called. This keyword can be used to refer data members or member functions of same class.

22. Differentiate between abstract class and concreate class

Ans: definition is given above in notes.

23. Define polymorphism.

Ans: definition is given above in notes.

24. What is dynamic dispatch?

Ans: Method overriding is one of the ways in which Java supports Runtime Polymorphism.
Dynamic method dispatch is the mechanism by which a call to an overridden method is
resolved at run time, rather than compile time. When an overridden method is called through
a superclass reference, Java determines which version(superclass/subclasses) of that method
is to be executed based upon the type of the object being referred to at the time the call
occurs. Thus, this determination is made at run time.

25. What is the difference between next() and next line() in Java?

Ans: next() reads the string before the space. it cannot read anything after it gets the first
space and nextLine() reads the whole line.

26. Can string objects created using new operator?

Ans: we create Strings like "abcd" but not like new String("abcd") in Java because every time
you refer to "abcd", you get a reference to a single String instance, rather than a new one
each time. So you will have:
String a = "abcd";
String b = "abcd";

a == b; //True
but if you had

String a = new String("abcd");


String b = new String("abcd");
then it's possible to have

a == b; // False

Superior Group of Collage Jauharabad 36 | P a g e

You might also like