4131 Object Oriented Programming(Java)
4131 Object Oriented Programming(Java)
4131 Object Oriented Programming(Java)
1. Characteristics of OOP
❖ Object-Oriented Development (OOD):
OOD organizes software design around objects, combining data and behavior.
❖ Classes and Objects:
Classes define blueprints for objects, while objects are instances of classes.
❖ Encapsulation:
Encapsulation hides internal object details and exposes only necessary
functionality, enhancing security and modifiability.
❖ Abstraction:
Abstraction hides complex implementation details, focusing on essential object
features.
❖ Inheritance:
Inheritance allows a new class to inherit attributes and methods from an existing
class, promoting code reuse and extensibility.
❖ Polymorphism:
Polymorphism allows objects of different classes to be treated uniformly,
enabling methods to behave differently based on object type.
2. Features of Java programming or advantages of Java
3. Class
Class is a blueprint for which objects are created. It defines all properties and behavior of
the object.
Syntax:
class class_name{
// body of the class
}
Eg:
Class Example{
public static void main (String[] args){
System.out.println(“Hello world”);
}
}
4. Object
An object is the entity of the class it has its properties and behaviors.
The syntax of creating an object is given below:
class_name object_name = new class_name();
Eg: Consider a class Example the object of the class is created as
Example obj = new Example();
5. Overloading in Java
In a class more than one method with the same name and different arguments is called
overloading. It is identified by the Java compiler based on the method's differing number
or types of arguments.
Eg :
class Calculator {
public void add(int a, int b) {
System.out.println(“Sum of the 2 numbers = ”+(a+b));
}
public void add(int a, int b, int c) {
System.out.println(“Sum of the 3 numbers = ”+(a+b+c));
}
public static void main(String[] args){
Calculator obj= new Calculator();
obj.add(5, 10);
obj.add(5, 10, 15);
}
}
6. Constructor:
A constructor is a special type of member function with the same name as the class. It is
used to initialize the members of the class. In Java, constructors have no explicit return
type. Unlike methods, constructors are automatically invoked when objects are created.
There are two types of constructors in Java:
}
}
7. Access Modifiers
In Java, access modifiers are keywords used to control the visibility or accessibility of
classes, variables, methods, and constructors. They define who can access a particular
class, member, or constructor. The four access levels are −
❖ default: Visible to the package. No modifiers are needed.
❖ private: Visible to the class only
❖ public: Visible to the world.
❖ protected: Visible to the package and all subclasses
The table given below shows the detailed behaviour of the access specifiers:
8. Exception Handling
Exception handling in Java is a mechanism to handle runtime errors, known as exceptions,
gracefully. An exception is an event that disrupts the normal flow of a program's execution.
Keywords used for Exception Handling:
❖ try: The try block is used to enclose the code that may throw exceptions.
❖ catch: The catch block is used to handle exceptions caught by the try block. It specifies
the type of exception to catch and the code to execute when that exception occurs.
❖ finally: The finally block is used to execute code that should always run, regardless of
whether an exception is thrown or not. It is typically used for cleanup tasks such as
closing files or releasing resources.
Eg:
class DivisionExample {
public static void main(String[] args) {
int a= 10;
int b= 0;
try {
System.out.println("Result of division: " + (a/b));
} catch (ArithmeticException e) {
System.out.println("Error: Division by zero is not allowed.");
}
finally{
System.out.println(“This code will always execute.”);
}
}
}
9. Polymorphism (Static and dynamic binding)
Polymorphism is derived from two Greek words, “poly” and “morph”, which mean
“many” and “forms”, respectively. Hence, polymorphism meaning in Java refers to the
ability of objects to take on many forms.. There are two types:
Module 2
1. Inheritance
The ability of the class to derive the property and attributes from another class
inheritance. It promotes code reusability and avoids redundancy. There are mainly
4 types of inheritance in Java.
1. Single Level Inheritance:
Single level inheritance refers to the inheritance relationship where a subclass
inherits from only one superclass. In this type of inheritance, there is a single level
of hierarchy between classes. Example: Class B extends Class A.
2. Multi-level Inheritance:
Multi-level inheritance refers to the inheritance relationship where a subclass
inherits from another subclass, creating a chain of inheritance. In this type of
inheritance, there are multiple levels of hierarchy between classes. Example:
Class C extends Class B, and Class B extends Class A.
3. Hierarchical Inheritance:
Hierarchical inheritance refers to the inheritance relationship where multiple
subclasses inherit from the same superclass. In this type of inheritance, there is a
single superclass with multiple subclasses branching out from it. Example: Class
B and Class C both extend Class A.
4. Hybrid Inheritance:
Hybrid inheritance refers to a combination of two or more types of inheritance,
such as single level, multi-level, or hierarchical inheritance. It involves the use of
multiple inheritance paths to create complex class hierarchies. Example: Class D
extends Class B and Class C, where Class B extends Class A, resulting in a
combination of hierarchical and multi-level inheritance.
Eg : program to demo Hybrid inheritance
class A{
public void functionA()
{
System.out,println(“This is a method of class A”);
}
}
class B extends A{
public void functionB()
{
System.out,println(“This is a method of class B”);
}
}
class C extends A{
public void functionC()
{
System.out,println(“This is a method of class C”);
}
}
class D extends B{
public void functionD()
{
System.out,println(“This is a method of class D”);
}
}
class Hybrid{
class B extends A {
public void functionA() {
System.out.println("FunctionA in class B");
}
}
3. Super Keyword Or How to invoke super class constructor using super keyword
It can be used to access superclass members (variables or methods) and constructor from within
the subclass.
Super Keyword to invoke super class members
We can use super keyword to access a variable or method from base class using the super
keyword see the program given below.
class Parent {
Output
Parent name: John
Child name : Roy
Eg:
abstract class A {
public abstract void displayOne();
class Example {
public static void main(String[] args) {
B objB = new B();
objB.displayOne();
objB.displayTwo();
}
}
1. Final Class: When a class is declared as `final`, it means that it cannot be subclassed or
inherited by other classes. It serves as a complete, unchangeable entity. For example:
3. Final Variable: When a variable is declared as `final`, its value cannot be changed after
it's initialized, making it a constant. For instance:
class Example {
final int constantValue = 10;
}
Here, `constantValue` cannot be reassigned to a different value once initialized.
6. Interface in Java
In Java, an interface is a reference type similar to a class, but it only contains abstract method
declarations. Here are some key properties of interfaces:
❖ Abstract Methods: Interfaces can only contain method signatures without method bodies.
These methods are implicitly public and abstract.
❖ Default Access Modifier: By default, all members (methods and constants) in interfaces
are public and abstract, meaning they can be accessed by any class that implements the
interface.
❖ Constants: Interfaces can also contain constants, which are implicitly public, static, and
final.
❖ Multiple Inheritance: In java multiple inheritance is posible using inheritance.
❖ Polymorphism: Interfaces enable polymorphism, allowing different classes to implement
the same interface with their specific implementations.
Eg:
interface ExampleInterface {
// Method signatures
public abstract void method1();
public abstract void method2();
// Constant declaration
static final int CONSTANT_VALUE = 10;
}
7. Package in Java
Package in Java is a collection of related classes, interfaces, and methods. It promotes code
modularity and prevents naming conflicts.
Types of packers
1. Built-in packages: These are the packages provided by Java, such as java.lang, java.util,
etc., which contain essential classes and interfaces for Java programming.
2. User-defined Packages: These are custom packages created by developers to organize their
classes and interfaces. User-defined packages help manage larger projects by grouping
related classes together.
Eg:
package mathOperations;
import mathOperations.Arithmetic;
Module 3
1. What is GUI?
GUI is a user interface that allows users to interact with digital devices, software, or
operating systems using graphical elements such as icons, buttons, and menus.
2. What is swing? What are the features?
Swing is a GUI tool kit in Java used by developers to create graphical user interfaces. It
provides a set of components like buttons, text fields, and panels, which can be used to
build interactive graphical interfaces.
Features of swing
1. Swing is a part of JFC (Java Foundation Classes)
2. Swing is built on top of AWT (Abstract Window Toolkit)
3. Swing components are lightweight
4. Swing components have pluggable look and feel
5. Swing components are platform-independent
6. Swing components are included in the package javax.swing
3. Components of swing
Swing as has many components which helps to build user interfaces in java some of the main
components of the swings are:
1. JButton: Used for triggering actions or events.
2. JLabel: Displays text or images on the interface.
3. JTextField: Enables users to input single-line text.
4. JTextArea: Allows users to input and display multi-line text.
5. JCheckBox: Presents options for selection in a checkbox format.
6. JRadioButton: Enables users to select a single option from multiple choices.
7. JComboBox: Offers a drop-down list for selecting from multiple options.
8. JList: Displays a list of items for selection.
9. JTable: Presents data in a tabular format with rows and columns.
10. JPanel: Acts as a container for organizing and grouping other components.
4. Describe steps to create and manipulate GUI controls.
1. Create Frame: Instantiate a JFrame object to serve as the main window.
2. Add Components: Add Swing components (e.g., JButton, JLabel) to the frame using
layout managers like BorderLayout or GroupLayout.
3. Set Component Properties: Customize each component by setting properties such as size,
text, font, color, etc.
4. Register Event Listeners: Attach event listeners (e.g., ActionListener) to components to
handle user interactions like button clicks.
5. Pack and Display: Pack the frame to adjust its size based on the components and make it
visible to the user.
5. How can we handle Mouse events in Java?
Mouse events in Java are handled by two interfaces MouseListener and MouseMotionListener
these interfaces have various methods to handle different events of mouse they are listed below.
MouseListener Interface:
1. void mouseClicked(MouseEvent e): Called when the mouse is clicked on a component.
2. void mousePressed(MouseEvent e): Called when a mouse button is pressed on a
component.
3. void mouseReleased(MouseEvent e): Called when a mouse button is released on a
component.
4. void mouseEntered(MouseEvent e): Called when the mouse enters a component.
5. void mouseExited(MouseEvent e): Called when the mouse exits a component.
MouseMotionListener Interface:
1. void mouseDragged(MouseEvent e): Called when the mouse is dragged (moved with a
button pressed) on a component.
2. void mouseMoved(MouseEvent e): Called when the mouse is moved (without any button
pressed) on a component.
6. How can we handle keyboard events in Java?
Keyboard events in Java are handled using the KeyListener interface. This interface provides
methods to respond to various keyboard interactions. Here are the methods:
KeyListener Interface:
1. void keyPressed(KeyEvent e): Called when a key is pressed.
2. void keyReleased(KeyEvent e): Called when a key is released.
3. void keyTyped(KeyEvent e): Called when a key is typed (pressed and released).
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int x = Integer.parseInt(tf1.getText());
int y = Integer.parseInt(tf2.getText());
JOptionPane.showMessageDialog(frame, "Sum = " + (x + y));
}
});
frame.add(lbl1);
frame.add(lbl2);
frame.add(tf1);
frame.add(tf2);
frame.add(btn);
}
}
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(frame, "Button Clicked!");
}
});
frame.add(button);
frame.setLayout(null);
frame.setVisible(true);
}
}
frame.addMouseMotionListener(new MouseMotionListener() {
public void mouseMoved(MouseEvent e) {
System.out.println("Mouse Moved");
}
frame.addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent e) {
System.out.println("Key Pressed: " + e.getKeyChar());
}
frame.add(button);
// Set the frame focusable and request focus
frame.setFocusable(true);
frame.requestFocusInWindow();
}
}
import javax.swing.*;
import java.awt.event.*;
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Button Clicked!");
}
});
frame.addMouseMotionListener(new MouseMotionListener() {
public void mouseMoved(MouseEvent e) {
System.out.println("Mouse Moved");
}
frame.addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent e) {
System.out.println("Key Pressed: " + e.getKeyChar());
}
frame.add(button);
3. What is JDBC
JDBC (Java Database Connectivity) is a Java API for connecting Java applications to
databases. It provides methods for establishing connections, executing SQL queries, and
processing results. With JDBC, Java programs can interact with various databases, making
it a crucial tool for database-driven applications.
4. What are the steps or stages of implementing JDBC
1. Load JDBC Driver: Use `Class.forName()` to load the JDBC driver class for your
database.
- Example: `Class.forName("com.mysql.jdbc.Driver");`
5. Process Results: Retrieve data from the ResultSet using `rs.getXXX()` methods and
iterate through the results.`
6. Close Connection: Close the connection when done with database operations using
`Connection.close()`.
- Example: `conn.close();`
5. Explain the Prepared statement, execute statement and result set in JDBC
❖ PreparedStatement
In JDBC, a PreparedStatement is a precompiled SQL statement that allows
parameterized queries to be executed more efficiently. It helps prevent SQL
injection attacks and improves performance by preparing the query once and
executing it multiple times with different parameters.
❖ ExecuteStatement
An ExecuteStatement is a general interface for executing SQL statements. It's used
to execute static SQL queries, such as INSERT, UPDATE, DELETE, or any other
SQL statement that doesn't require parameters.
❖ ResultSet
A ResultSet is an object that represents the result set of a database query. It
provides methods to traverse through the data retrieved from the database, retrieve
column values, and navigate through rows. ResultSet objects are typically returned
when executing SELECT queries using either Statement or PreparedStatement.
import java.sql.*;
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(url, uname, pass);
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query);
rs.next();
String name = rs.getString("username");
System.out.println(name);
st.close();
con.close();
}
}
try {
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection(url, username, password);
PreparedStatement preparedStatement = connection.prepareStatement(query);
preparedStatement.close();
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
8. Write a program to perform an update query in JDBC.
import java.sql.*;
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection(url, username, password);
PreparedStatement preparedStatement = connection.prepareStatement(query);
preparedStatement.close();
connection.close();
}
}