Understanding Object Oriented Programming
Understanding Object Oriented Programming
The advantages of abstraction are: Inheritance ➤ It plays an important role in allowing objects
➤ Flexibility in approach ects o Inheritance is the process by which objects having different internal structures to share
➤ Enhanced security of one class acquire the properties of objects of external interface.
➤ Easier replacement another class. ➤ Polymorphism is extensively used in
➤ Modular approach Ex: child inherits properties from parents. implementing inheritance.
Encapsulation The keyword used for inheritance is 'extends' ➤ Compile time polymorphism is also known as
Abstraction and encapsulation are complementary The main advantages of inheritance are code static polymorphism or early binding
concepts. Abstraction focuses upon the reusability, maintainability and reduce costs Run time polymorphism also known as dynamic
observable behaviour of an object, encapsulation ➤ A class whose properties are inherited is called polymorphism or late binding
focuses upon the implementation that gives rise to parent class or super class or base class. Modularity
this behaviour. A class which inherits the properties are called ➤It is the process of decomposing a problem
Encapsulation is the mechanism of wrapping the child class or sub class or derived class. (program) into a set of modules to reduce overall
data (variables) and code (methods) into a single ➤ The new class inherits the attributes and complexity of the problem.
unit. behaviour of pre-existing class. ➤ Breaking up codes into small modules that
➤ It is implemented though the concept of classes The sub class can inherits features of super class perform a specific task.
that is, data and methods combined combined into with adding their own new features ➤ It enables reusability and minimizes duplication.
a single unit. Different types of inheritance are: Message passing
➤ It is protective shield that prevent data accessed ➤ Single Inheritance: A subclass derived from ➤ Objects can communicate each other by
from outside. single super class. sending and receiving each other like the same
➤ Using encapsulation, data in one class is hidden ➤ Multi-level inheritance: When there is a chain of way people pass message to one another.
from another class, so also known as data hiding. inheritance. ➤ Objects can communicate through its methods.
➤ Encapsulation makes it possible for objects to ➤ Hierarchical Inheritance: A class has number of ➤ Message passing involves specifying the name
be treated like 'black boxes'. sub classes. of object, name of method and the information to
be sent.
Polymorphism
Eg: [Link](name)
➤ Polymorphism means ability to take more than
Calling method of an object from another object is
one forms.
called message passing.
SIMPLE JAVA PROGRAM| HELLO WORLD EXAMPLE Java Control Statements | Control Flow in Java Decision-Making statements:
// Your First Program class Java compiler executes the code from top to ➤ As the name suggests, decision-making
HelloWorld bottom. The statements in the code are statements decide which statement to execute
{ executed according to the order in which they and when.
public static void main(String[] args) appear. Java provides three types of ➤ Decision-making statements evaluate the
{ control flow statements. Boolean expression and control the program flow
[Link]("Hello, World!"); } } 1. Decision Making statements depending upon the result of the condition
if statements provided.
Adding Numbers with Overloaded Methods switch statement ➤ There are two types of decision- making
class Calculator { 2. Loop statements statements in Java, i.e., If statement and switch
// Method 1: add two integers do while loop statement.
int add(int a, int b) { return while loop 1) If Statement:
a + b; } for loop ➤ In Java, the "if" statement is used to evaluate a
// Method 2: add three integers int for-each loop condition.
add(int a, int b, int c) { return a + b + c; } 3. Jump statements ➤ The control of the program is diverted
// Method 3: add two double numbers break statement depending upon the specific condition.
double add(double a, double b) { return a + continue statement ➤ The condition of the If statement gives a
b; } Boolean value, either true or false.
public static void main(String[] args) { Java continue statement ➤ In Java, there are four types of if-statements
Calculator calc = new Calculator(); Unlike break statement, the continue statement 1. Simple if statement
[Link]("Add 2 int: " + [Link](5, 10)); doesn't break the loop, 2. if-else statement
// Calls method 1 It skips the specific part of the loop and jumps to 3. if-else-if ladder
[Link]("Add 3 int: " + [Link](5, 10, the next iteration of the 4. Nested if-statement
15)); // Calls method 2 loop immediately. Nested if-statement
[Link]("Add 2 double: " + [Link](5.5, Continue has two form both labeled and In nested if-statements, the if statement can
6.5)); // Calls method3 unlabeled contain an if or if-else statement inside another if
} } or else-if statement.
APPLETS Driver: This interface handles the communications Creating a JDBC Application
Applet is a special type of program that is with the database server. You will interact directly There are six main steps involved in building a
embedded in the webpage to generate the dynamic with Driver objects very rarely. Instead, you use JDBC application:
content. It runs inside the browser and works at Driver Manager Objects, which manages objects of 1. Import the packages: Include the packages that
client side. this type. It also abstracts the details associated contain the JDBC classes required for database
An applet can be a fully functional Java application with working with Driver objects. programming. Most often, using import [Link].*; is
because it has the entire Java API at its disposal. Connection: This interface with all methods for sufficient.
There are some important differences between an contacting a database. The connection object 2. Register the JDBC driver: Initialize the driver to
applet and a standalone Java application, including represents communication context, i.e., all establish a communication channel with the
the following: communication with database is through database.
An applet is a Java class that extends the connection object only. 3. Open a connection: Use the
[Link] class. Statement: You use objects created from this [Link]() method to create a
A main() method is not invoked on an applet, and interface to submit the SQL statements to the Connection object, which represents a physical
an applet class will not define main(). database. Some derived interfaces accept connection to the database.
Applets are designed to be embedded within an parameters in addition to executing stored 4. Execute a query: Create an object of the
HTML page. procedures. Statement type to build and submit SQL
Common JDBC Components ResultSet: These objects hold data retrieved from statements to the database.
The JDBC API provides the following interfaces and a database after you execute an SQL query using 5. Extract data from the result set: Use the
classes Statement objects. It acts as an iterator to allow appropriate methods to retrieve and process data
Driver Manager: This class manages a list of you to move through its data. from the ResultSet.
database drivers. Matches connection requests SQLException: This class handles any errors that 6. Clean up the environment: Explicitly close all
from the java application with the proper database occur in a database application. database resources (such as Connection,
driver using communication sub protocol. The first Statement, and ResultSet) instead of relying on the
driver that recognizes a certain sub protocol under JVM's garbage collection.
JDBC will be used to establish a database
Connection.
Graphical User Interface (GUI) AWT (Abstract Window Toolkit) in Java Checkbox
A Graphical User Interface (GUI) allows users to It is a part of Java's standard library ([Link] Components that exist in dual state checked &
interact with an application through graphical package). unchecked
components instead of text commands. This package contains all of the classes for creating Constructors
GUI components include windows, frames, panels, user interfaces and for painting graphics and 1. checkBox() creates a new checkbox
buttons, text fields, text areas, lists, combo boxes, images. 2. checkBox(String label) - creates a new checkbox
labels, checkboxes, etc. AWT is used to create Graphical User Interfaces specified label
Key Features: (GUIs) in Java applications. 3. checkBox(String label, boolean state) - es a new
GUI allows users to raise events (e.g., clicking a It provides a set of pre-built classes for creating checkbox with the specified label and state
button, typing in a text field, closing a window) and windows, buttons, menus, text fields, labels, etc. (checked or unchecked)
provides responses to those events. AWT is platform-dependent, meaning it uses the Methods
ABI GUI makes applications user-friendly, native GUI components of the operating system. 1. getLabel()- retrieves the label of the checkbox
interactive, and visually appealing. AWT is a part of Java Foundation Classes (JFC) 2. setLabel(String text) - sets the label of the
It is entirely event-driven, meaning user actions along with Swing and other GUI toolkits. checkbox
trigger events that the application handles. It follows event-driven programming, meaning it 3. boolean getState()-returns the status of checkbox
Graphics in AWT responds to user actions like button clicks, key 4. setState(Boolean b) - sets the state of checkbox
Graphics Class Choice
presses, etc.
In GUI applications, we can use Graphics class of The Choice class is used to create a pop-up list of
[Link] package to create various graphics like lines, Button items from which the user may choose.
rectangles, circles, polygons etc. A push button is a component that contains a label The Choice control is a form of menu.
Methods available in the Graphics class: and that generates an event when it is pressed. To add a selection to the list, call add().
void drawLine(int startX, startY, endX, endY) - Used to Push buttons are objects of type Button. It has this general form:
draw a line between two points. Button defines these two constructors: void add(String name)
void drawRect(int startX, int startY, int width, int Button()
height) - Used to draw a rectangle starting Button(String str)
from the top left corner with the given width and
height. The coordinates of the top left corner of the
rectangle are startX and startY.
add(String item, int index) - adds the specified item
Label TextField
at the specified index position
Used for displaying a single line of text in a that accepts text input in a single line
getItemCount() - retrieves the no. of items in the
container Are:-
list
Constructors Textfield() creates a new textfield
getSelectedItem() - retrieves the selected item
Label() creates an empty label Textfield(int col) - creates a new textfield with
from the list
Label(String text) - creates a label with specified given no. of columns, col
getSelectedIndex() - retrieves the index of selected
text Textfield(String s) - creates a new textfield
item from the list
Label(String text, int align) - creates a label with TextArea initialized with default text,s
specified text aligned left or right or centre User interface component that accepts text input in a What is an event?
Methods multiple line Change in the state of an object is known as event
getAlignment()-retrieves the current alignment of Constructors are: i.e. event describes the change in state of source.
the label Textarea()-creates a new textarea
Events are generated as result of user interaction
setAlignment(int pos) sets the alignment of the Textarea (int row, int col) - creates a new textarea with
with the graphical user interface components.
label given no. of rows, row and columns, col
For example, clicking on a button, moving the
getText() retrieves the value of the label Textarea (String s) - creates a new textarea initialized
mouse, entering a character through keyboard,
setText(String s) - sets the value of the label to a with default text,s
Textarea (String s, int r, int col, int scrollbar) - creates a
selecting an item from a list, scrolling the page are
List new textarea initialised with default text, the activities that causes an event to happen.
List control is a scrollable list of text items that s and given no. of rows and columns and visibility of Types of Event
enables you to select either 1 item or multiple items scrollbar The events can be broadly classified into two
Constructors Methods categories:
[Link]()creates a new scrolling list of items getColumns() returns the no. of columns of the ForegroundEvents
2. list(int rows, boolean multipleselection) -creates a textarea These are events that occur due to direct user
new scrolling list of items with required rows and getText()returns the text contained in the textarea
interaction with GUI components. They are
also enables to select more than I item from the list setText()sets textarea
generated as consequences of a person
Methods getRows()returns of the textarea
interacting with the graphical components in
add(String item) adds the specified item at the end insert(String str, int position) insert the required text
Graphical User Interface. For example, clicking on
of the list at the specified position in the textarea
i ld
a button, moving the mouse, entering a character EVENT HANDLING Type Casting Type Conversion
through the keyboard, selecting an item from a list, hould hay Event Handling is the mechanism that Type casting is a
scrolling the page, etc. controls the event and decides what should mechanism in which Type conversion allows
BackgroundEvents happen if an event occurs. This mechanism have one data type is a compiler to convert
These are events that occur without direct user the code which is known as event handler that is converted to another one data type to
interaction and are usually generated by the executed when an event occurs. data type using a another data type at the
system or hardware. Operating system interrupts, Java Uses the Delegation Event Model to handle casting () operator by a compile time of a
hardware or software failure, timer expires, an the events. This model defines the standard programmer. program or code.
operation completion are the example of mechanism to generate and handle the events. The It can be used both Type conversion is only
background events. Delegation Event Model has the following key compatible data type used with compatible
Delegation Event Model participants namely: and incompatible data data types, and hence it
The modern approach to handling events Source: The source is an object on which event type. does not require any
Defines standard and consistent mechanisms to occurs. Source is responsible for providing It requires a casting operator
generate and process events. information of the occurred event to its handler. programmer to It does not require any
Its concept is quite simple: a source generates an Java provide as with classes for source object. manually casting one programmer
event and sends it to one or more listeners. Listener: It is also known as event handler. Listener data into another type. intervention to convert
In this scheme, the listener simply waits until it is responsible for generating response to an event. It is used while one data type to
receives an event. From java implementation point of view the designing a program by another because the
Once received, the listener processes the event listener is also an object. Listener waits until it the programmer. compiler automatically
and then returns. receives an event. Once the event is received, the compiles it at the run
Listener must register with source to receive event listener process the event a then returns. time of a program.
notification. Event Object: the class object which describes the It is used or take place
event. at the compile time of a
program.