2-1 Lab Manual Oop
2-1 Lab Manual Oop
Preface
Object-oriented programming (OOP) is a programming paradigm that uses abstraction to create models based
on the real world. It utilizes several techniques from previously established paradigms, including modularity,
polymorphism, and encapsulation. In OOP, each object is capable of receiving messages, processing data, and
sending messages to other objects. Each object can be viewed as an independent little machine with a distinct
role or responsibility. Object-oriented programming is intended to promote greater flexibility and
maintainability in programming, and is widely popular in large-scale software engineering. By virtue of its
strong emphasis on modularity, object oriented code is intended to be simpler to develop and easier to
understand later on, lending itself to more direct analysis, coding, and understanding of complex situations
and procedures than less modular programming methods. There are principles that work in OOP, such as
encapsulation, inheritance, polymorphism and Abstraction.
This lab will enable students to learn basic OOP concepts with the help of Java Language i.e., class-based
modeling, Inheritance, Polymorphism, Abstraction interface, exceptional handling and GUI.
Objective
To strengthen problem solving ability by using the characteristics of an object-oriented approach.
To design applications using object-oriented principles and features
To differentiate OOP and Procedural programming
To handle Exceptions in programs.
To Handle and Debug Errors and Bugs in a program
To learn about latest software development tools and IDEs
Tools/ Technologies
1. Java, JDK, Net beans
2. MS Access, M-SQL, Ucanaccess
Effectiveness
The student will acquire required skills and knowledge to develop applications using object-oriented concepts.
They will gain the ability to analyze given problems from object-oriented programming dimensions and select
appropriate OOP principles to implement it. The students will demonstrated satisfactory skills for including
OOP concepts in general software systems.
2
BS (Computer Science) 2023
Weekly Breakdown
3. Create an overloaded constructor for Calculator and create object using both
constructors
Create an Interface CalcIntf, implement its functions in CalculatorImpl and finally
create the object CalcIntf object in TestApp.
Differentiate between the accessibility of functions using objects of CalcIntf and
CalculatorImpl.
Implement multiple interfaces in a single class.
4. Create a parent class “Account” with three variables num, title and bal with two
functions withdraw and deposit.
Create a child class “SavingAccount” with a function calculateProfit (that applies
7.5%
profit on current balance).
Finally create the class “TestApp” that creates the object of Saving account and call
withdraw, deposit functions.
Override withdraw function in SavingAccount to deduct Rs. 250 if the balance after
withdrawal of amount is less than 10000.
5. Use of this, super, protected and finally keywords.
Creating multiple objects of the same class.
Use of netbeans to create window forms, get values from text fields and action on
button.
6. Design a calculator in netbeans with two text boxes and implement the functionality of
+, -, * and /.
Similarly modify the logic to use single text field for calculations.
Call the functions of Calculator class to provide the functionality.
7. Implementaion of Layout Manger in order to set layout of different Containers
i.e. JFrame etc.
Use of BorderLayout for JPanel and JFrame
GridLayout to used to generate Gradient display
3
BS (Computer Science) 2023
8. Creating and importing packages using netbeans and console based apps.
Catch the Arithmetic Exception for divide function in above calculator.
9. Create a new database in MSAccess2007 and then create a student table with its basic
attributes.
Design a Form in netbeans to insert information of a student.
Write code behind the button to connect with database, write query and then execute
it.
Code Overview of used functions, classes and interfaces from javadoc.
10. Create new class DbConn containing a connection string and a single function to
insert,
update and delete records. It takes query as input and return boolean.
Error correction in search and update records.
Create another function in DbConn to search records that returns the ResultSet.
11. Get a list of products from table and display it in Combo box in Sales Form.
Also add menus with menu items and handle the click events using netbeans.
Add a combo box and add values using properties.
12. Create a package containing interface and classes and the import to call functions in
TestApp class.
Get details of products and display it in JTable,
Opening multiple forms from main page and login form creation.
Validation of input fields and use regular expressions.
4
BS (Computer Science) 2023
TABLE OF CONTENTS
Preface ............................................................................................................................................................... 2
Objective ........................................................................................................................................................... 2
Tools/ Technologies .......................................................................................................................................... 2
Effectiveness ..................................................................................................................................................... 2
Weekly Breakdown .......................................................................................................................................... 3
LAB 1: Class, Object, Constructor ................................................................................................................ 6
LAB 2: Overloading, import Header Files .................................................................................................... 7
LAB 3: Inheritance .......................................................................................................................................... 8
LAB 4: Interfaces and polymorphism............................................................................................................ 9
LAB 5: GUI Components .............................................................................................................................. 10
LAB 6: GUI Components .............................................................................................................................. 11
LAB 7: Layout Managers .............................................................................................................................. 12
LAB 8: Database Connectivity->insert Query ............................................................................................ 15
LAB 9: Database Connectivity, SQL Update and Select query................................................................. 16
LAB 10: GUI/Database Connectivity using layered Architecture ............................................................ 18
LAB 11: GUI/Database Connectivity using layered Architecture ............................................................ 20
LAB 12: GUI/ layered Architecture/JTable ................................................................................................ 23
5
BS (Computer Science) 2023
Objectives:
To learn how to implement class, object, constructor
Create, compile and run java files using command prompt
Theoretical Description:
Create a class Calculator with two variables, a constructor with no parameter and two functions for add and
multiply. Create a class TestApp with a main function and create object of Calculator class to call functions.
Lab Task(s):
Calculator.java TestApp.java
public class Calculator public class TestApp
{ {
int x, y;
public TestApp() {
public Calculator() { }
}
public static void main(String args[])
int sum(int a, int b) {
{ Calculator obj=new Calculator();
return a+b; int n = obj.sum(10,20);
} System.out.println("Sum=" + n);
int mul(int a, int b) int m=obj.mul(5,6);
{ System.out.println("mul="+m);
return a*b; }
} }
}
6
BS (Computer Science) 2023
Objectives:
To learn how to implement overloading
To learn how to import Header Files
Theoretical Description:
Create a class Calculator with two variables, a constructor with no parameter and two functions for add and
multiply. Add functionality for overloading sum and multiply. Also call scientific functions using Math class.
Create a class TestApp with a main function and create object of Calculator class to call functions.
Lab Task(s):
Calculator.java TestApp.java
public class Calculator public class TestApp
{ {
int x, y;
public TestApp() {
public Calculator() { }
}
public static void main(String args[])
int sum(int a, int b) {
{
return a+b; Calculator obj=new Calculator();
}
int s = obj.sum(10,20);
int sum(int a, int b, int c) System.out.println("Sum=" + s);
{ double s1 = obj.sum(15.5,56.7);
return a+b+c; System.out.println("Sum=" + s1);
} s = obj.sum(15,25,10);
System.out.println("Sum=" + s);
double sum(double a, double b)
{ int m=obj.mul(5,6);
return a+b; System.out.println("mul="+m);
} double m1=obj.mul(59.7,66.6);
System.out.println("mul="+m1);
int mul(int a, int b)
{ System.out.println("sin="+Math.sin(55.6));
return a*b; System.out.println("sin="+Math.pow(5,3));
}
}
double mul(double a, double b) }
{
return a*b;
}
7
BS (Computer Science) 2023
LAB 3: Inheritance
Objectives:
To learn how to implement overloading
To learn how to import Header Files
Theoretical Description:
Create a parent class “Account” with three variables num, title and bal with two functions withdraw and
deposit. Create a child class “SavingAccount” with a function calculateProfit (that applies 7.5% profit on
current balance). Finally create the class “TestApp” that creates the object of Saving account and call
withdraw, deposit functions. Override withdraw function in SavingAccount to deduct Rs. 250 if the balance
after withdrawal of amount is less than 10000.
.
Lab Task(s):
Account.java SavingAccount.java TestApp.java
public class Account public class SavingAccount public class TestApp
{ extends Account { {
public String acct_num; public SavingAccount(){ public TestApp() {
public String acct_title; } }
public double acct_bal; public static void main(String args[])
public void withdraw (double {
public Account(){ amt) SavingAccount s = new
} { SavingAccount ();
public void withdraw if (acct_bal > amt)
(double amt) acct_bal -= amt; s.acct_num = “01-01-999888”;
{ if (acct_bal < 10000) s.acct_title = “MyAcctTitle”
if (acct_bal > amt) acct_bal -= 250; s.acct_bal = 10000.0;
acct_bal -= amt; }
} public double calculateProfit () s.withdraw (2000.0);
{ System.out.println
public void deposit (double double profit = acct_bal * ("Balance="+s.acct_bal);
amt) 0.075; }
{ acct_bal += profit; }
acct_bal += amt; return profit;
} }
} }
8
BS (Computer Science) 2023
Objectives:
To learn how to implement interfaces and polymorphism
Theoretical Description:
Create an interface for two functions for add and multiply. Create a class Calculator with two class level
variables, a parameterized overloaded constructor and four functions for add, subtract, divide and multiply.
Create a class TestApp with a main function and create object of Calculator interface to call functions.
Lab Task(s):
CalcIntf.java CalculatorImpl.java TestApp.java
public interface CalcIntf public class Calculator public class TestApp
{ { {
public int sum(int a,int b); int x, y; public TestApp() {
public int mul(int a,int b); }
} public Calculator() { public static void main(String args[])
} {
CalcIntf obj=new CalculatorImpl();
int sum(int a, int b) int n = obj.sum(10,20);
{ System.out.println("Sum=" + n);
return a+b; int m=obj.mul(5,6);
} System.out.println("mul="+m);
int mul(int a, int b)
{ //Not accessible to call
return a*b; //int m=obj.div(5,6);
}
int div(int a, int b) CalculatorImpl calc=new CalculatorImpl();
{ int result = calc.sum(10,20);
return a/b; System.out.println("Sum=" + result);
} result = calc.mul(5,6);
int sub(int a, int b) System.out.println("Product="+ result);
{ result = calc.div(20,4);
return a-b; System.out.println("Division="+ result);
} result = calc.sub(9,3);
System.out.println("Difference="+ result);
} }
}
9
BS (Computer Science) 2023
Objectives:
To start with GUI components i.e. JFrame, JTextField, JButton, JLabael, Event Handling
Theoretical Description:
Create a class Calculator with two variables, a constructor with no parameter and two functions for add and
multiply. Use netbeans to create window forms with two text fields and two buttons for plus and multiply.
Write code behind button to take values from text fields and create object of Calculator class to call functions
by passing parameters.
Lab Task(s):
Calculator.java CalculatorForm.java
public class Calculator public class CalculatorForm extends JFrame
{ {
int x, y;
public CalculatorForm() {
public Calculator() { }
}
public void btnPlusActionPerformed(ActionEvent e)
int sum(int a, int b) {
{ int v1=Integer.parseInt(txtval1.getText());
return a+b; int v2=Integer.parseInt(txtval2.getText());
}
int mul(int a, int b) Calculator obj=new Calculator();
{ int s = obj.sum(v1,v2);
return a*b; lblOutput.setText(“Sum = ” +s);
} }
} }
Output:
10
BS (Computer Science) 2023
Objectives:
To start with GUI components i.e. JFrame, JTextField, JButton, JLabael, Event Handling
Theoretical Description:
Create a Simple Calculator e.g. Windows Calculator. Use netbeans to create window forms with single text
fields and provide functionality for plus, minus multiply C, 1,2, MR, M+, MC. Write code behind buttons to
take values from text field and implement the intended functionality.
Lab Task(s):
CalculatorForm.java
public class SimpleCalculator extends JFrame public void btnEqualsActionPerformed(ActionEvent e){
{ int r=0;
int v1, v2, opt=0, mem; v2= Integer.parseInt(txtval1.getText());
Output:
11
BS (Computer Science) 2023
Theoretical Description:
1. Use of FlowLayout to load JButtons dynamically .
2. Use of BorderLayout
3. Use of Gridlayout for gradient display
Lab Task(s):
//FlowLayout
import javax.swing.*;
import java.awt.*;
public class Statics1 {
public static void main(String[] args) {
new S1GUI();
}
}
class S1GUI {
private JFrame f;
public S1GUI() {
f = new JFrame("Statics1");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(500, 200);
f.setLayout(new FlowLayout(FlowLayout.LEFT));
for (int b = 1; b < 9; b++)
f.add(new JButton("Button " + b));
f.setVisible(true);
}
}
//Border Layout
import javax.swing.*;
import java.awt.*;
12
BS (Computer Science) 2023
13
BS (Computer Science) 2023
14
BS (Computer Science) 2023
Theoretical Description:
Design a Form in netbeans to insert information of a student. Write code behind the button to connect with
database, write query and then execute it.
Lab Task(s):
StudentForm.java
public void btnInsertActionPerformed(ActionEvent e)
{
String reg_num = tfregNum.getText();
String name = tfName.getText();
String cell_num = tfCellNum.getText();
String adrs = tfAdrs.getText();
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection conn = DriverManager.getConnection("jdbc:odbc:Driver={MicroSoft Access Driver
(*.mdb)};DBQ=C:\\JavaProjects\\dbName");
Statement stmt = conn.createStatement();
stmt.execute(query);
conn.close();
JOptionPane.showMessageDialog(null,"INSERTED SUCCESSFULLY");
}
catch(java.lang.ClassNotFoundException ex)
{
JOptionPane.showMessageDialog(null,"Exception Occured"+ex.getMessage());
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(null,"Exception Occured"+ex.getMessage());
}
}
Output:
15
BS (Computer Science) 2023
Theoretical Description:
Design a Form in netbeans to Search on the basis of registration number and fill remaining information of a
student. Also provide functionality to update record Write code behind the button to connect with database,
write query and then execute it.
Lab Task(s):
StudentForm.java
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
16
BS (Computer Science) 2023
Output:
17
BS (Computer Science) 2023
To Learn Database Connectivity using separate class/ layered Architecture, SQL insert, Update and Selec
query
Theoretical Description:
Create new class DbConn containing a connection string and a single function to insert, update and delete
records. It takes query as input and return boolean. Create another function in DbConn to search records that
returns the ResultSet.Design a Form in netbeans to Search on the basis of registration number and fill
remaining information of a student. Also provide functionality to update record Write code behind the button
to connect with database, write query and then execute it.
Lab Task(s):
DbConn.java
import java.sql.*;
public class DbConn {
public static String connString="jdbc:odbc:Driver={MicroSoft Access Driver
(*.mdb)};DBQ=C:\\JavaProjects\\dbName";
18
BS (Computer Science) 2023
19
BS (Computer Science) 2023
To Learn Database Connectivity using separate class/ layered Architecture, SQL insert, Update and Selec
query
JCombobox, JTextField, JButton etc.
Theoretical Description:
Create DbConn class like in task 8. Get a list of products from database table and display it in Combo box in
Sales Form on Window Opened Event. Provide the functionality to select the product from combo box and
display the stock and unit price from Product table in database. Subtract the number of items sold from the
stock and then update the stock in Product table. Finally insert sales record in Sales table.
Lab Task(s):
DbConn.java
import java.sql.*;
public class DbConn {
public static String connString="jdbc:odbc:Driver={MicroSoft Access Driver
(*.mdb)};DBQ=C:\\JavaProjects\\dbName";
21
BS (Computer Science) 2023
Output:
22
BS (Computer Science) 2023
JTable, ResultSet
Theoretical Description:
Create a class DbConn. Design a Form in netbeans to view all records from database table and fill data in
JTable on Product form.
Lab Task(s):
DbConn.java
ProductForm.java
Private void btnShowAllActionPerformed(java.awt.event.ActionEvent evt) {
String title=cmbtitle.getSelectedItem().toString();
String query = "Select * from Product Where prdTitle='" + title + "'";
try {
ResultSet rs = obj.Search(query);
while(rs.next()) {
for(int j=1; j<=8;j++)
{
prdTable.setValueAt(rs.getString(j).toString(),i, j-1);
}
i++;
}
}
catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Exception Occured" + ex.getMessage());
}
}
Output:
23