Lab Manual OOP LAB
Lab Manual OOP LAB
Lab1 ..................................................................................................................................................... 5
Topics Covered .......................................................................................................................................... 5
Arrays ........................................................................................................................................................ 7
Lab2 ..................................................................................................................................................... 9
Topics Covered .......................................................................................................................................... 9
Lab3 ................................................................................................................................................... 12
Topics Covered ........................................................................................................................................ 12
Constructor ......................................................................................................................................... 12
Lab4 ................................................................................................................................................... 15
Topics Covered ........................................................................................................................................ 15
Inheritance .......................................................................................................................................... 15
Lab5 ................................................................................................................................................... 18
Topics Covered ........................................................................................................................................ 18
Abstraction: ......................................................................................................................................... 18
2
Sample Lab Exercises .............................................................................................................................. 20
Lab7 ................................................................................................................................................... 22
Topics Covered ........................................................................................................................................ 22
Lab8 ................................................................................................................................................... 23
Topics Covered ........................................................................................................................................ 23
Exception............................................................................................................................................. 23
Lab9 ................................................................................................................................................... 24
Topics Covered ........................................................................................................................................ 24
Socket .................................................................................................................................................. 24
Lab10 ................................................................................................................................................. 26
Topics Covered ........................................................................................................................................ 26
Thread ................................................................................................................................................. 26
Collection ............................................................................................................................................ 26
Lab11 ................................................................................................................................................. 28
Topics Covered ........................................................................................................................................ 28
GUI-Graphics ....................................................................................................................................... 28
Lab12-Presentation ............................................................................................................................ 30
Presentation on Project .......................................................................................................................... 30
3
Introduction
Course Outcome
• Describe the Object Oriented Programming Features.
• Able to analyze a problem and develop well designed applications using the OOP features.
• Use a modern/popular IDE to develop the application.
• Be able to use the Library effectively.
• Develop self-driven project using the concepts learned from course and their own research.
4
Lab1
Topics Covered
• Introduction to Java
• Tools Set-up
• Java Basics
o Application Class
o Naming convention
o Programming Language Basics
o Arrays
Introduction to Java
JAVA was developed by Sun Microsystems Inc in 1991, later acquired by Oracle Corporation. It was
developed by James Gosling and Patrick Naughton.
Tools Set-Up
Step1: Install Java and Path Set-up
• Need to install Java(JDK and JRE). Get the latest version from Java Standard Edition(SE) from
http://www.oracle.com/technetwork/java/javase/downloads/index.html
o After installing Java you need to set-up the “Path” environment variable which is available
from My Computer under Advanced Properties tab.
Note: Do not delete anything in “Path” variable. Just add your path “C:\Program
Files\Java\jdk1.8.0_31\bin;” (Depending on your version the path will change) at the beginning of the
existing value.
5
Step 2: Install IDE
Java Basics
Application Class
• The class that contains “main” method.
o No stand alone functions in Java - All code is part of a class
• When an application is launched, the “main” method of this class gets executed.
• Example application class:
Method body
Standard output to
print something.
System.out.println()
• Used to print a text
• System - is a class in Java API (Application Program Interface)
6
• out - represents the standard output, static member of System, part of API
• println() – method to print the text
Note:
• Java assumes that you will be using a GUI for input from the user Hence there is no
"simple" way to read input from a user
• Later it is simplified by introducing “Scanner” class in Java Library – we will cover this
topic later.
Naming Convention
• All java source file should end with .java
• Each .java file can contain only one public class
• The name of the file should be the name of the public class plus ".java"
• Do not use abbreviations in the name of the class
• If the class name contains multiple words then capitalize the first letter of each word ex.
HelloWorld.java
• It’s a good practice to have one class per file
Arrays
• Declaration and creating Array object
int[] sampleArray;
sampleArray = new int[10];
Or
int[] sampleArray = new int[10];
• Initialization
o During declaration
int[] sampleArray = {1,2,3,4,5};
o After declaration
int[] sampleArray;
sampleArray = new int[]{1,2,3,4,5};
7
Sample Lab Exercises
1. Write the “Hello World” program.
Steps to follow:
• Open the IDE.
• Open a new Project named “Hello World”
• Open a new Class named “HelloWorld” ( no space in the name)
• Add the main method if it is not already added
public static void main(String[] args){
}
• Add the following statement inside the main method to print/display the text “Hello World!”
System.out.println(“Hello World!”);
• Save the file
• Now run the project from the menu bar or using the icon
3. Write a Java program that will go through the items of an array and find the max and min value.
Take the following values as the input of the array
8
Lab2
Topics Covered
• Introduction to OOP
Introduction to OOP
• All computer programs consist of two elements:
o Logic (coded in functions) and data.
• In “C” we always think about action and implement the action using a function. Here the
function takes input data, processes it, and produces output data.
• But in Object-oriented programming (OOP) model, program is organized around “objects”
rather than "actions". Object is defined by a class.
• Class has 2 types of member
o Fields/Attributes – represented by instance variables
o Actions/Behaviors – represented by method
Structure/Format of Class
<modifier> class <class name>{
// Declare attributes
<modifier> <data type> <attribute name>;
<modifier> <data type> <attribute name> [=<value >] ;
// Constructor
<modifier> <class name> (<argument>){
<statements>;
}
// Method
<modifier> <return type > <method name>(<argument>){
<statements>;
}
} // end of class
9
public void updateCgpa(int credit, float gpa){
cgpa = (cgpa*creditCompleted + credit*gpa)/(creditCompleted+credit);
creditCompleted = creditCompleted + credit;
}
public float getCgpa(){
return cgpa;
}
}
// update cgpa
studentR.updateCgpa(3, 4.0f);
Output:
10
Sample Lab Exercises
1. Create a class named “Box” which has 3 attribute: length, width, height and a method named
getVolume(). getVolume() method will calculate the volume of the Box and return the value.
From “main” method create 2 Box objects with different length, width, height, then call the
getVolume() method and print the volumes.
2. Create an Address Book application, where a user can create new record, update record, delete
record.
3. Create a Banking Application, where a user can create new account, deposit money, withdraw
money and check the balance.
11
Lab3
Topics Covered
• Class/Object, Constructor,
• package, access modifier
• getter/setter
• Array (Reference Type)
• User input
o Scanner
o JOptionPane (GUI)
Constructor
• A constructor
o Allocate space for instance variables.
o Initializes an object (its instance variables) immediately upon creation.
• Syntax:
o It has the same name as the class.
o Syntactically similar to a method. Except has no return type. Not even void.
This is because the implicit return type of a class’ constructor is a reference of
class type itself.
• If no constructor is specified in a class, Java provides a parameter-less default constructor.
Example
Constructor
12
Without constructor/ With default constructor With explicit constructor
public static void main(String[] args) { public static void main(String[] args) {
// Create object // Create object
Student student = new Student();
Student student = new Student("Rashid",
// Assign values to attributes "011153001", 3.0f, 50);
student.name = "Rashid";
student.id = "011153001"; // display cgpa before update
student.cgpa = 3.0f; System.out.println("Credit Completed: "+
student.creditCompleted = 50; student.creditCompleted +"; Previous cgpa: "+
student.cgpa);
// display cgpa before update
System.out.println("Credit Completed: "+ // Calling method - update cgpa
student.creditCompleted +"; Previous cgpa: "+ student.updateCgpa(3, 4.0f);
student.cgpa); student.updateCgpa(3, 4.0f);
student.updateCgpa(3, 4.0f);
// Calling method - update cgpa
student.updateCgpa(3, 4.0f); // display cgpa after update
student.updateCgpa(3, 4.0f); System.out.printf("Credit Completed: %d; New
student.updateCgpa(3, 4.0f); cgpa: %.2f",
student.creditCompleted,student.cgpa);
// display cgpa after update
System.out.printf("Credit Completed: %d; }
New cgpa: %.2f",
student.creditCompleted,student.cgpa);
}
}
User Input
Example:
13
double dInput = Double.parseDouble(input); // Convert String to double
Output:
14
Lab4
Topics Covered
• Inheritance
• Method override
• SubClass Polymorphism
Inheritance
• Inheritance is the process by which one object acquires the properties of another object.
• It is a way to form new classes using classes that have already been defined.
• The new classes (child classes), take over (or inherit) attributes and behavior of the pre-existing
classes (parent classes).
Name of the
Example
Child Class
Inheritance
keyword
Name of the
Parent Class
15
Output:
Parent Method
In Child ParentVariable=10, ChildVariable=5
Parent Method
10
Method override
• A class replacing an ancestor's implementation of a method with an implementation of it own.
• When overriding a method in child class
o Method Signature(name and argument list) and return type must be the same as the
parent method.
o Child method could be equal or more accessible.
Example:
Parent class’s
method
SubClass Polymorphism
• A parent class reference is used to refer to a child class object.
• Couple things to remember:
16
o The only possible way to access an object is through a reference variable.
o The type of the reference variable would determine the methods that it can invoke on the
object.
• Using subclass polymorphism we can call or execute the child-class overriding method by the
parent-class object
Example
17
Lab5
Topics Covered
• Abstraction
o Abstract Class
o Interface
• ArrayList
• static keyword
Abstraction:
• Abstraction is a process of hiding the implementation details from the user, only the
functionality will be provided to the user.
• In other words, the user will have the information on what the object does instead of how it
does it.
• In Java, abstraction is achieved using
• Abstract classes and
• interfaces
Abstract Class
An abstract class is a class that is incomplete, in that it describes a set of operations, but is missing the
actual implementation of these operations. Abstract classes:
• Cannot be instantiated.
• So, can only be used through inheritance.
// Constructors
Animal(){ }
Animal(String name, String color, double weight){
this.name = name;
this.color = color;
this.weight = weight;
}
// Concrete methods
public void eat(){ System.out.println(name + " eats."); }
// abstract methods
public abstract void makeSound();
}
18
class Bird extends Animal{
public Bird() { name = "Bird"; }
@Override
public void makeSound() { System.out.println("Chirp"); }
}
@Override
public void makeSound() { System.out.println("Roar"); }
}
Interface
• Using interface, you can specify what a class must do, but not how it does it.
o Interfaces can specify public methods but might not have the implementation of
methods.
• Once it is defined, any number of classes can implement an interface.
• Also, one class can implement any number of interfaces.
Example: Interface
interface Flyable{
String media = "Sky";
void fly();
boolean needFuel();
}
@Override
public boolean needFuel() { return false; }
}
@Override
public boolean needFuel() { return true; }
}
20
Lab6 – Mid Exam
Mid Exam
21
Lab7
Topics Covered
• Graphical User Interface(GUI)
3. Create a GUI application where clicking a button will check/uncheck a CheckBox and also change the
text of the button. Clicking the button will
b. Check/Select the checkbox if it is not checked/selected. Also set the text of the Button
to “UnCheck”.
c. Uncheck/Unselect the checkbox if it is checked/selected. Also set the text of the Button
to “Check”.
22
Lab8
Topics Covered
• Exception
• Input / Output (will use BufferedReader, BufferedWriter, PrintWriter, Scanner)
Exception
• An exception is an event, which occurs during the execution of a program that disrupts the normal
flow of the program's instructions.
• Following are some scenarios where an exception occurs.
o A user has entered an invalid data.
o A file that needs to be opened cannot be found.
o A network connection has been lost in the middle of communications or the JVM has run
out of memory.
• We need to handle the exception using try-catch-finally block to avoid abnormal shutdown of the
program.
2. Assume a file “input.txt” contains comma-separated numbers. Write an application to read the
numbers from the “input.txt” file, parse those numbers, calculate the summation, and then
write the result to a different file name “output.txt”.
23
Lab9
Topics Covered
• Socket
Socket
Socket is the Java programming model to establish a two-way communication link between two
programs running on the network.
import java.io.*;
import java.net.*;
import java.io.*;
import java.net.Socket;
25
Lab10
Topics Covered
• Thread
• Socket
• Collections
Thread
Thread is an independent path of execution through program code.
Example:
System.out.println(Thread.currentThread().getName()
+":"+i);
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Collection
• Collection (sometimes called a container) is an object that holds other objects that are accessed,
placed, and maintained under some set of rules.
26
• Examples
o Sets
o List
o Map
2) Write a program to take numbers as input from user, add to an ArrayList and HashSet, and then
print the items in the List and Set. While running the application try to enter same numbers
multiple time and watch the changes in list and set.
27
Lab11
Topics Covered
• GUI-Graphics
GUI-Graphics
• All graphics are drawn relative to a window.
• The origin of each window is at the top-left corner and is 0,0.
• Coordinates are specified in pixels.
• A graphics context is encapsulated by the Graphics class.
• Two ways to obtain a graphics.
• It is passed to a method, such as paint( )/paintComponent() or update( ), as an
argument.
• It is returned by the getGraphics( ) method of Component.
• Graphics class defines a number of methods that draw various types of objects, such as lines,
rectangles, and arcs.
• Objects can be drawn edge-only or filled.
• Objects are drawn in the currently selected color, which is black by default.
Example:
import java.awt.*; Output
import javax.swing.*;
import java.awt.event.*;
public class DrawCircle extends JFrame {
int x = 90, y = 90, d=40;
public DrawCircle() {
setSize(200, 200);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
29
Lab12-Presentation
Presentation on Project
30