Oop Notes
Oop Notes
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
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
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.
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;
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:
public abstract class student { // making class abstract using abstract keyword
String name;
int age;
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();
}
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
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
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.
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
Example:
public class A
{
public void methodA()
{
System.out.println("Base class 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:
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.
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.
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
}
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 −
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
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
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.
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();
}
System.out.println("Car is accelerating");
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.
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:
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.
• 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.
String textFile;
String line;
obj.ReadTextFile("c:\\MyFile.txt");
}
}
String textFile;
public void WriteFile(String File)
{
textFile = File;
try {
FileWriter Writer = new FileWriter(textFile);
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");
}
}
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 −
I. Serializing an Object
The ObjectOutputStream class is used to serialize an Object.
import java.io.*;
public class Serialize{
try {
FileOutputStream fileOut =
new FileOutputStream("/tmp/employee.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
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 {
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).
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.
Example:
public static void main (String[] arrgs)
{
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
public TimeClass()
{
hour = minute = second = 0;
}
}
public int getHour() {
return hour;
}
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; }
month=m;
year=y;
}
}
}
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 class MainClass {
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();
}
@Override
public void Talk() {
system.out.println(“Crow 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 Rectangle() {
width=1;
length=1;
}
@Override
public double area() {
return width * length;
}
@Override
public void draw() {
system.out.println(“Rectangle is drawn”);
}
}
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 Oval() {
this(1,1);
}
@Override
public double area() {
return 3.14*a*b;
}
@Override
public void draw () {
system.out.println(“Oval is drawn”);
}
}
// 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();
}
}
}
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;
bufferedWriter.write(text);
bufferedWriter.newLine();
bufferedWriter.close(); // Always close files.
}
catch(Exception ex) {
System.out.println("Error writing to file");
}
}
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{
setLayout(null);
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);
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
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));
}
}
}
}
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”
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";
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;}
}
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.
private
protected
default
public
Ans:
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.
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
Ans: we can join two Java String fields using the + operator, for example
String firstName = "uzair";
String lastName = "salman";
String fullName = firstName + lastName;
Ans: there are data members as well as member function within a class to define an object
characteristics.
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.
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.
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
a == b; // False