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

Object Oriented Programming Short Note

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Object Oriented Programming Short Note

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

★ Structured Approach Vs.

Object-Oriented Approach

Structured Approach Object-Oriented Approach

Program is divided into a number of sub modules Program is organized by having a number of
or functions. classes and objects.

Function call is used. Message passing is used.

Problem oriented approach Problem domain oriented approach

Software reuse is not possible. Reusability is possible.

★ UML ( Unified Modeling Language )

UML is a standard modeling language for specifying, visualizing, constructing, and documenting the
artifacts of systems.UML is a pictorial language used to make system blueprints.

There are two main categories;

● structure diagrams

Structure diagrams show the things in the modeled system. In a more technical term, they
show different objects in a system.
1. Class Diagram
2. Component Diagram
3. Deployment Diagram
4. Object Diagram
5. Package Diagram
6. Profile Diagram
7. Composite Structure Diagram

● behavioral diagrams.

show what should happen in a system. They describe how the objects interact with each
other to create a functioning system.
1. Use Case Diagram
2. Activity Diagram
3. State Machine Diagram
4. Sequence Diagram
5. Communication Diagram
6. Interaction Overview Diagram
7. Timing Diagram

structure diagrams

1. Class diagram

This short note making resources are,google search engine,chat gpt and lecture slides
WhatsApp group (click on this/new syllabus notes only) Credit - Kanishka viraj
It describes the objects in a system and their relationships. Class diagram consists of
attributes and functions. Class diagrams are the only UML diagrams which can be mapped
directly with object oriented languages.

+ denotes - public attributes or operations


- denotes - private attributes or operations
# denotes - protected attributes or operations
~ denotes - package attributes or operations

Nortation / Class Relationships

1. Inheritance (or Generalization)

Inheritance is “is a relationship”. It has a parent class and its corresponding


child classes

2. Simple Association

A structural link between two peer classes.There is an association between


Class1 and Class2.consider we have two classes A and B where class A calls
class B and Class B also calls class A.

This short note making resources are,google search engine,chat gpt and lecture slides
WhatsApp group (click on this/new syllabus notes only) Credit - Kanishka viraj
3. Aggregation

A special type of association. It represents a "part of" relationship.


Class2 is part of Class1.

4. Composition

one class is dependent on another. One class is a part of the other.

5. Dependency

This short note making resources are,google search engine,chat gpt and lecture slides
WhatsApp group (click on this/new syllabus notes only) Credit - Kanishka viraj
Multiplicity

How many objects of each class take part in the relationships and multiplicity can be
expressed as:

● Exactly one - 1
● Zero or one - 0..1
● Many - 0..* or *
● One or more - 1..*
● Exact Number - e.g. 3..4 or 6
● Or a complex relationship - e.g. 0..1, 3..4, 6.* would mean any number of
objects other than 2 or 5

Question 1 -
Draw a class diagram for the following scenario in a hotel The following text describes the
proposed Hotel Reservation System.

A customer can view the hotel information and reserve a room online or visit the place and
reserve rooms. Rooms can be Single rooms, double rooms, or family rooms.If they are
online customers, the system will check the room availability and notify the customer
availability of rooms. If not, the receptionist does the task.When the customer makes the
payment, the room is allocated for them. Online customers should pay via credit cards and
others are allowed to pay by credit cards or cash payment.When the customer checks in the
system is updated. The customer can check out from the hotel at any time or extend after
informing the receptionist. It will be accepted if rooms are available

This short note making resources are,google search engine,chat gpt and lecture slides
WhatsApp group (click on this/new syllabus notes only) Credit - Kanishka viraj
Use case diagram

It consists of use cases, actors and their relationships. Use case diagrams are used at a
high level design to capture the requirements of a system. So it represents the system
functionalities and their flow.

Purpose of USE CASE diagrams

● Representing the goals of system-user interactions


● Defining and organizing functional requirements in a system
● Specifying the context and requirements of a system
● Modeling the basic flow of events in a use case

Above question use case diagram

Sequence Diagrams

Sequence DiagramsUML Sequence Diagrams are interaction diagrams that detail how
operations are carried out. They capture the interaction between objects in the context of a
collaboration.

Sequence Diagrams are time focused and they show the order of the interaction visually by
using the vertical axis of the diagram to represent time, what messages are sent and when.
This short note making resources are,google search engine,chat gpt and lecture slides
WhatsApp group (click on this/new syllabus notes only) Credit - Kanishka viraj
Purpose of Sequence Diagram

1. Visualize interactions between system components.


2. Understand system behavior through message sequencing.
3. Aid in system design and analysis.
4. Identify potential issues or bottlenecks.
5. Facilitate communication among stakeholders.
6. Act as valuable documentation for the system's dynamic behavior.

Notation -

1. Actors –
An actor in a UML diagram represents a type of role where it interacts with
the system and its objects.
external to the subject (i.e., in the sense that an instance of an actor is not a
part of the instance of its corresponding subject).

2. Lifelines –
A lifeline represents an individual participant in the Interaction

3. Activations -

A thin rectangle on a lifeline represents the period during which an element is


performing an operation.
The top and the bottom of the of the rectangle are aligned with the initiation
and the completion time respectively

This short note making resources are,google search engine,chat gpt and lecture slides
WhatsApp group (click on this/new syllabus notes only) Credit - Kanishka viraj
4. Call Message -

A message defines a particular communication between Lifelines of an


Interaction.Call message is a kind of message that represents an invocation
of operation of target lifeline.We represent messages using arrows.

5. Return Message -

Return message is a kind of message that represents the pass of information


back to the caller of a corresponding former message.

6. Create Message

Create message is a kind of message that represents the instantiation of


(target) lifeline.

This short note making resources are,google search engine,chat gpt and lecture slides
WhatsApp group (click on this/new syllabus notes only) Credit - Kanishka viraj
A sequence diagram for an emotion based music player

★ Fundamental of java

This short note making resources are,google search engine,chat gpt and lecture slides
WhatsApp group (click on this/new syllabus notes only) Credit - Kanishka viraj
● class keyword is used to declare a class in java.
● public keyword is an access modifier which represents visibility, it means it is visible to all.
● static is a keyword used to create a static method. no need to create object to invoke the
static method
● void is the return type of the method
● main represents the startup of the program.
● String[] args are used for command line arguments.
● System.out.println() is used as a print statement.

Data types

Data types are divided into two groups:

1. Primitive data types - byte, short, int, long, float, double, boolean and char
2. Non-primitive data types - such as String, Arrays and Classes

Operators

1. Assignment Operators
2. Arithmetic Operators
3. Relational Operators / Comparison Operators
4. Bitwise Operators
5. Logical Operators

1. Arithmetic Operators

This short note making resources are,google search engine,chat gpt and lecture slides
WhatsApp group (click on this/new syllabus notes only) Credit - Kanishka viraj
2. Assignment Operators

3. Relational Operators / Comparison Operators

4. Logical Operators

This short note making resources are,google search engine,chat gpt and lecture slides
WhatsApp group (click on this/new syllabus notes only) Credit - Kanishka viraj
5. Bitwise Operators

★ Control flow

control flow (or flow of control) is the order in which individual statements of a program are executed

Control flow structures

1. Sequential structure :

Default mode. Statements are executed from top to bottom of the program one by
one.

2. Selection structure:

Selection structure or conditional structure, is different blocks of code are performed


based on whether a boolean condition is true or false

If-else, switch-case

3. Repetition structure:

Same block of code is executed again and again based on whether a boolean
condition is true or false

while, do-while, for

If condition

syntax:

This short note making resources are,google search engine,chat gpt and lecture slides
WhatsApp group (click on this/new syllabus notes only) Credit - Kanishka viraj
If else condition

Syntax:

while loop

Syntax:

Do While loop

Syntax:

This short note making resources are,google search engine,chat gpt and lecture slides
WhatsApp group (click on this/new syllabus notes only) Credit - Kanishka viraj
For Loop

Syntax:

Switch Statement

This short note making resources are,google search engine,chat gpt and lecture slides
WhatsApp group (click on this/new syllabus notes only) Credit - Kanishka viraj
public class printswitch {
public static void main(String[] args) {
int Day = 4;
String DayString;
switch (Day) {
case 1:
DayString = "Sunday";
break;
case 2:
DayString = "Monday";
break;
case 3:
DayString = "Tuesday";
break;
case 4:
DayString = "Wednesday";
break;
case 5:
DayString = "Thursday";
break;
case 6:
DayString = "Friday";
break;
case 7:
DayString = "Saturday";
break;
default:
DayString = "Invalid Day";
break;
}
System.out.println(DayString);
}
}

★ break statement

Terminates the loop or switch statement and transfers execution to the statement immediately
following the loop or switch.

★ continue statement

continue statement is used in loops (such as for, while, or do-while) to skip the current iteration and
move to the next one/iteration.

★ Object Oriented Programming (OOP)

Object Oriented Programming (OOP) is a programming paradigm that focuses on the use of objects
to represent and manipulate data with real world concepts.

OOP concepts include,

This short note making resources are,google search engine,chat gpt and lecture slides
WhatsApp group (click on this/new syllabus notes only) Credit - Kanishka viraj
1. Inheritance
2. Abstraction
3. Encapsulation
4. Polymorphism

What Is a Class ?
A class is a blueprint or prototype from which objects are created

What Is an Object?
An object is a software bundle of related state and behavior.

Example of Class Object Creation and Usage

This short note making resources are,google search engine,chat gpt and lecture slides
WhatsApp group (click on this/new syllabus notes only) Credit - Kanishka viraj
★ Java constructor

A constructor in Java is a special method that is used to initialize objects. The constructor is called
when an object of a class is created. It can be used to set initial values for object attributes.

Note that the constructor name must match the class name, and it cannot have a return type (like
void).

There are two types of constructors in Java:

1. Default constructor (no-arg constructor)


2. Parameterized constructor

1. Default constructor (no-arg constructor)

output

2. Parameterized constructor

output

This short note making resources are,google search engine,chat gpt and lecture slides
WhatsApp group (click on this/new syllabus notes only) Credit - Kanishka viraj
★ Difference between constructor and method in Java

Constructor Java method

A constructor is used to initialize the state of an A method is used to expose the behavior of an
object. object.

A constructor must not have a return type. A method must have a return type.

The constructor is invoked implicitly. The method is invoked explicitly.

The constructor name must be the same as the The method name may or may not be the same as
class name. the class name.

The Java compiler provides a default constructor if The method is not provided by the compiler in any
you don't have any constructor in a class. case.

★ Inheritance

A class that inherits from another class can reuse the methods and fields of that class.
Java, Inheritance means creating new classes based on existing ones.it is possible to inherit
attributes and methods from one class to another. Multiple inheritance is not supported in java.

● superclass (parent / Base) - the class being inherited from


● subclass (child / Derived) - the class that inherits from another class

To inherit from a class, use the extends keyword.


Animal.java (Parent class) answer

This short note making resources are,google search engine,chat gpt and lecture slides
WhatsApp group (click on this/new syllabus notes only) Credit - Kanishka viraj
Dog.java (Child class)

—-------------------------------------------------------------------------------------------------------------------------------------------

Animal.java

This short note making resources are,google search engine,chat gpt and lecture slides
WhatsApp group (click on this/new syllabus notes only) Credit - Kanishka viraj
cat.java

Answer

This short note making resources are,google search engine,chat gpt and lecture slides
WhatsApp group (click on this/new syllabus notes only) Credit - Kanishka viraj
Advantages
● Code reusability
● Reduce duplicate code
● Reduce development time and effort
● Provide specialization
● Extendibility
- Can extend an already made classes by adding new features

Disadvantage
● Tide coupling
● When the no of inheriting levels are increasing , maintenance is difficult

★ Encapsulation

The meaning of Encapsulation is to make sure that "sensitive" data is hidden from users.
To achieve this, you must:
declare class variables/attributes as private
provide public get and set methods to access and update the value of a private variable

Person.java output , John

Main.java

Super Keyword in Java

The super keyword in Java is a reference variable which is used to refer to an immediate
parent class object.

Whenever you create the instance of a subclass, an instance of the parent class is created
implicitly which is referred to by a super reference variable.

This short note making resources are,google search engine,chat gpt and lecture slides
WhatsApp group (click on this/new syllabus notes only) Credit - Kanishka viraj
Usage of Java super Keyword
● super can be used to refer to an immediate parent class instance variable.
● super can be used to invoke the immediate parent class method.
● super() can be used to invoke immediate parent class constructor

this Keyword in Java

this keyword refers to the current object in a method or constructor.

Usage of Java this keyword

● this can be used to refer to the current class instance variable.


● this can be used to invoke current class method (implicitly)
● this() can be used to invoke the current class constructor.
● this can be passed as an argument in the method call.
● this can be passed as an argument in the constructor call.
● this can be used to return the current class instance from the method.

★ Polymorphism

polymorphism is a feature that allows you to provide a single interface to varying entities of the
same type.

Polymorphism means "many forms", and it occurs when we have many classes that are related to
each other by inheritance.

Same name to different operations


● Overriding
● Overloading

1. Overriding

If a subclass (child class) has the same method as declared in the parent class, it is known
as method overriding in Java.

Known as runtime polymorphism. A method declared final cannot be overridden. Static


methods are not possible to override

Advantages
● Provide specific implementation for object
● Provide specific implementation for a method that is already provided by its super
class.

Output

This short note making resources are,google search engine,chat gpt and lecture slides
WhatsApp group (click on this/new syllabus notes only) Credit - Kanishka viraj
2. Overloading

With method overloading, multiple methods can have the same name with different
parameters:
ex-
int myMethod(int x)
float myMethod(float x)
double myMethod(double x, double y

Answer

This short note making resources are,google search engine,chat gpt and lecture slides
WhatsApp group (click on this/new syllabus notes only) Credit - Kanishka viraj
Advantages of overloading

● Increases the readability


- call a similar method for different types of data
● providing multiple behavior to same object with respect to attributes of object

Constructor overloading
A class can have two or more different implementations by having different
constructors.

Output

This short note making resources are,google search engine,chat gpt and lecture slides
WhatsApp group (click on this/new syllabus notes only) Credit - Kanishka viraj
Test.java

This short note making resources are,google search engine,chat gpt and lecture slides
WhatsApp group (click on this/new syllabus notes only) Credit - Kanishka viraj
★ Abstraction

Abstraction is the process of hiding certain details and only showing the essential features of the
object.
Hiding the implementation details from the user
Abstraction can be achieved with either abstract classes or interfaces

Advantages
● Hiding implementation complexity from user
● Object is easy to used by users

The abstract keyword is a non-access modifier, used for classes and methods:

● Abstract class - is a restricted class that cannot be used to create objects (to access it, it
must be inherited from another class).

● Abstract method - can only be used in an abstract class, and it does not have a body. The
body is provided by the subclass (inherited from).

This short note making resources are,google search engine,chat gpt and lecture slides
WhatsApp group (click on this/new syllabus notes only) Credit - Kanishka viraj
Interfaces

An interface is a completely "abstract class" that is used to group related methods with
empty bodies:

To access the interface methods, the interface must be "implemented" (kinda like inherited)
by another class with the implements keyword (instead of extends). The body of the
interface method is provided by the "implement" class:

This short note making resources are,google search engine,chat gpt and lecture slides
WhatsApp group (click on this/new syllabus notes only) Credit - Kanishka viraj
★ Exception Handling

Exception handling is the process of responding to unwanted or unexpected events when a


computer program runs.

★ Program Errors

1. Syntax errors

Caused by an incorrectly written code such as misspelled keyword or variable, and


incomplete code

2. Runtime errors

Occurs when a statement attempts an operation that is impossible to carry out


Ex: division by zero

3. Logical errors

Occurs when code compiles and runs without generating an error, but the result produced is
incorrect

★ Types of Java Exceptions

1. Checked exceptions

● Occurs at the compile time


● Also called as compile time exceptions.
● Cannot be ignored at the time of compilation by programmers.
● All exceptions are checked exceptions

2. Unchecked
- Runtime exceptions
● At the time of execution.
● Never checked
● These include programming bugs, such as logic errors or improper use of an API.

This short note making resources are,google search engine,chat gpt and lecture slides
WhatsApp group (click on this/new syllabus notes only) Credit - Kanishka viraj
- Errors

● Not exceptions at all, but problems that arise beyond the control of the user or the
programmer.
● Errors are typically ignored in your code because you can rarely do anything about
an error.

● For example, if a stack overflow occurs, an error will arise. They are also ignored at
the time of compilation.

★ try catch block

The try statement allows you to define a block of code to be tested for errors while it is being
executed.

The catch statement allows you to define a block of code to be executed, if an error occurs in the try
block.

This short note making resources are,google search engine,chat gpt and lecture slides
WhatsApp group (click on this/new syllabus notes only) Credit - Kanishka viraj
catch ( Exception e ) {
System.out.println ( "Something went wrong." ); - we can use this
}

Output

★ Multiple catch block

★ finally Block

A finally block of code always executes, whether or not an exception has occurred.

★ Throwable

The Java throw keyword is used to explicitly throw an exception.Superclass of all errors and
exceptions.The throw statement allows you to create a custom error.

This short note making resources are,google search engine,chat gpt and lecture slides
WhatsApp group (click on this/new syllabus notes only) Credit - Kanishka viraj
The throw statement is used together with an exception type. There are many exception types
available in Java: ArithmeticException, FileNotFoundException, ArrayIndexOutOfBoundsException,
SecurityException, etc:

Output

This short note making resources are,google search engine,chat gpt and lecture slides
WhatsApp group (click on this/new syllabus notes only) Credit - Kanishka viraj
★ Nesting try blocks

Output

★ Swing

Swing API is set of extensible GUI Components to create JAVA Front End/ GUI Applications

Swing features

● Light Weight
● Rich controls
● Highly Customizable
● Pluggable look-and-feel- SWING

SWING - Controls

This short note making resources are,google search engine,chat gpt and lecture slides
WhatsApp group (click on this/new syllabus notes only) Credit - Kanishka viraj
Frame

This short note making resources are,google search engine,chat gpt and lecture slides
WhatsApp group (click on this/new syllabus notes only) Credit - Kanishka viraj
JOptionPane

● Display a message (through the use of the showMessageDialog method)


● Ask for user's confirmation (using the showConfirmDialog method)
● Obtain the user's input (using the showInputDialog method)
● Do the combined three above (using the showOptionDialog method)

This short note making resources are,google search engine,chat gpt and lecture slides
WhatsApp group (click on this/new syllabus notes only) Credit - Kanishka viraj
● JOptionPane.PLAIN_MESSAGE- This type simply displays the message in a dialog box
without any specific icon.
● JOptionPane.INFORMATION_MESSAGE - Displays an information icon along with the
message.
● JOptionPane.WARNING_MESSAGE - Shows a warning icon along with the message.
● JOptionPane.ERROR_MESSAGE - Displays an error icon along with the message.
● JOptionPane.QUESTION_MESSAGE - Shows a question mark icon along with the
message.

★ Event

java.awt.event
Package defines classes and interfaces used for event handling in the AWT and Swing.

import javax.swing.*;
import java.awt.event.*;

public class LoginFrame {


public static void main(String[] args) {
JFrame frame = new JFrame("Login");

JLabel userName = new JLabel("Username:");


userName.setBounds(50, 30, 80, 25);
JTextField usanameInput = new JTextField();
usanameInput.setBounds(130, 30, 150, 25);

JLabel password = new JLabel("Password:");


password.setBounds(50, 70, 80, 25);
JPasswordField passwordInput = new JPasswordField();
passwordInput.setBounds(130, 70, 150, 25);

JButton loginButton = new JButton("Login");


loginButton.setBounds(130, 110, 80, 25);

This short note making resources are,google search engine,chat gpt and lecture slides
WhatsApp group (click on this/new syllabus notes only) Credit - Kanishka viraj
// Action Listener for the login button
loginButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String username = usanameInput.getText();
String password = String.valueOf(passwordInput.getPassword());

//Perform login validation (Replace with actual validation logic)


if (username.equals("user") && password.equals("password")) {
JOptionPane.showMessageDialog(frame, "Login successful!");
} else {
JOptionPane.showMessageDialog(frame, "Invalid username or
password.", "Login Error", JOptionPane.ERROR_MESSAGE);
}
}
});

frame.add(userName);
frame.add(usanameInput);
frame.add(password);
frame.add(passwordInput);
frame.add(loginButton);

frame.setSize(350, 200);
frame.setLayout(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
—-------------------------------------------------------------------------------------------------------------------------------------------

★ Difference between AWT and Swing

Java AWT Java Swing

AWT components are platform-dependent. Java swing components are platform-independent.

AWT components are heavyweight. Swing components are lightweight.

AWT doesn't support pluggable look and feel. Swing supports pluggable look and feel.

This short note making resources are,google search engine,chat gpt and lecture slides
WhatsApp group (click on this/new syllabus notes only) Credit - Kanishka viraj
AWT provides less components than Swing Swing provides more powerful components such as
tables, lists, scrollpanes, colorchooser, tabbedpane
etc.

AWT doesn't follows MVC (Model View Controller) Swing follows MVC.

★ Stream

Java uses the concept of stream to make I/O operation fast.A stream is a sequence of data

● System.out: standard output stream

System.out.println("simple message");

● System.in: standard input stream

int i=System.in.read();
//returns ASCII code of 1st character

● System.err: standard error stream

System.err.println("error message");

FileOutputStream class

This short note making resources are,google search engine,chat gpt and lecture slides
WhatsApp group (click on this/new syllabus notes only) Credit - Kanishka viraj
FileInputStream class

This short note making resources are,google search engine,chat gpt and lecture slides
WhatsApp group (click on this/new syllabus notes only) Credit - Kanishka viraj
★ JDBC (Java Database Connectivity)

JDBC stands for Java Database Connectivity. JDBC is a Java API to connect and execute the query
with the database.

★ What is API ?

API (Application programming interface) is a document that contains a description of all the features
of a product or software.

★ Java Database Connectivity

There are 5 steps to connect any java application with the database using JDBC. These steps are
as follows:

1. Register the Driver class


2. Create connection
3. Create statement
4. Execute queries
5. Close connection

This short note making resources are,google search engine,chat gpt and lecture slides
WhatsApp group (click on this/new syllabus notes only) Credit - Kanishka viraj
Java Database Connectivity with MySQL

Driver class: The driver class for the mysql database is com.mysql.jdbc.Driver.

Connection URL:
The connection URL for the mysql database is jdbc:mysql://localhost:3306/sonoo
where jdbc is the API, mysql is the database, localhost is the server name on which
mysql is running, we may also use IP address, 3306 is the port number and sonoo is
the database name. We may use any database, in such case, we need to replace the
sonoo with our database name.

Username:
The default username for the mysql database is root.

Password:
It is the password given by the user at the time of installing the mysql database

first create a table in the mysql database

create database stu;


create table student (id int,name varchar(10),marks int);

import java.sql.*;

class MysqlCon {
public static void main(String args[]) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306
/stu", "root", " ");

// here stu is database name, root is username and password is empty


Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select * from student");
while (rs.next())
System.out.println(rs.getInt(1) + " " + rs.getString(2) + " " +
rs.getString(3));
con.close();
} catch (Exception e) {
System.out.println(e);
}
}
}

This short note making resources are,google search engine,chat gpt and lecture slides
WhatsApp group (click on this/new syllabus notes only) Credit - Kanishka viraj

You might also like