0% found this document useful (0 votes)
4 views5 pages

Understanding Object Oriented Programming

The document provides an overview of Object Oriented Programming (OOP) concepts such as classes, objects, inheritance, encapsulation, and polymorphism, emphasizing their roles in software development. It explains the advantages of OOP, including modularity and abstraction, and introduces Java's features, including its virtual machine and data types. Additionally, it covers Java control statements, including decision-making, loop, and jump statements, along with a simple Java program example.

Uploaded by

aparna.offical28
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)
4 views5 pages

Understanding Object Oriented Programming

The document provides an overview of Object Oriented Programming (OOP) concepts such as classes, objects, inheritance, encapsulation, and polymorphism, emphasizing their roles in software development. It explains the advantages of OOP, including modularity and abstraction, and introduces Java's features, including its virtual machine and data types. Additionally, it covers Java control statements, including decision-making, loop, and jump statements, along with a simple Java program example.

Uploaded by

aparna.offical28
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

1.

Object Oriented Programming (OOP) Class


OOPS Concepts (Principles of OOP/
OOP is a programming paradigm based on the ➤ A class is a blue print or template from which
Characteristics of OOP) aract
concept of objects. objects are created.
Object , Class, Abstraction , Encapsulation,
Object oriented means we organize our software as ➤ Consists of number of objects that is, It is an
Inheritance , Polymorphism , Modularity
a combination of different types of objects that abstract description of set of objects.
Message Passing
incorporates both data and behavior. ➤ It represents the set of properties or methods
Object
OOPs is a methodology that simplify software that are common to all objects of one type.
Each object represents a part of real world
development and maintenance by providing some ➤ A class is a collection of objects that have
problem.
rules. identical properties, common behaviour and
An object is a collection of data members and
The primary purpose of OOP is to increase shared relationship.
associated member functions.
flexibility and maintainability of program. Once the class is defined, multiple objects of that
Objects contains data in the form of fields known
class can be created.
Procedure oriented programming (POP) as attributes and code in the form of procedures
➤Classes are user defined data types.
Programs are made up of modules, which can be known as methods.
➤A class implementation consists of two parts: an
coded and tested separately and then assembled Each object has a state (its current data) and some
interface and an implementati
to form a complete program. POP is basically behaviour/operations (methods it can perform).
Interface: outside view of the class, visible to
consists of writing list of instructions for the Example: Dog is an object it has state (name, color,
anyone.
computer to follow and organizing these breed, etc) and behavior (barking, fetching,
Implementation: actual code that implements the
instructions into groups known as functions. It running, etc)
behaviour of class
follows top down approach. Objects help us divide a big problem into small
parts; each object handles its own data and Abstraction
actions. It is the process of hiding the details and exposing
Each Objects is member of particular class. So, only the essential features of a particular concept
objects is an instance of a class or object.
Data inside an object is protected and not freely Example: Using mobile phone, we call just by
shared outside. touching the call button without bothering how the
call get connected through transmitting signals.

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.

Features of object orientation ฀ Identity BYTE CODE


฀ Attribute Property of an object which distinguishes from all What is Bytecode?
Characteristics of an object are known as other objects is an identity. Single or ฀ Bytecode is the intermediate code generated by
properties or attributes of an object. They are group of activities can be identity of an object. the Java compiler.
individual things that differentiate one object from Eg: for student object, rollno is an identity ฀ It is a .class file that is platform-independent.
another. Attributes are variables name, gender, phnno is also considered as identity ฀ The Java Virtual Machine (JVM) reads and
insides a class that hold data also called fields or ฀ Operation executes this bytecode.
properties. An operation is a service that can be requested ฀ Bytecode makes Java a "Write Once, Run
Eg: name, age, weight, height in a Person class. from any object of the class to affect Anywhere" language.
฀ State behaviour. DATA TYPES IN JAVA
An object’s state is defined by its attributes. It is simply calling a behaviour. Data types specify the different sizes and values
State of an object includes current value of all its that can be stored in the
attributes. variable. There are two types of data types in Java
JAVA VIRTUAL MACHINE (JVM)
Eg: if a person object has name = “Ravi” and age = Primitive data types: The primitive data types
฀ Java Virtual Machine (JVM) is an abstract
25, that is its current state. include boolean, char, byte, short,
machine.
An attribute can be static (value will not change) or int, long, float and double.
฀ It is a part of Java that runs Java programs.
dynamic (value will be change). Non-primitive data types: The non-primitive data
฀ JVM converts Java bytecode (compiled .class
Eg: for a student object name, rollno, gender are types include Classes, Interfaces,
file) into machine code (which your computer
static and age, phoneno are dynamic and Arrays.
understands).
฀ Behaviour ฀ It makes Java platform-independent – the JAVA KEYWORDS
These are the methods (functions) that define same Java program can run on Windows, Linux, Java keywords are also known as reserved words.
what the objects can do. Behaviours are Mac, etc. Keywords are particular
tasks that an object performs. It defines operation words that act as a key to a code. These are
performed on an object. predefined words by Java so
Eg: walk(), speak() in a Person class. they cannot be used as a variable or object name
or cla ss name.
List of some Java Keywords ➡➡➡
1. abstract: Java abstract keyword is used to INTRODUCTION TO JAVA Programs run inside a virtual machine, which
declare an abstract class. An abstract class can The language is designed to have as few controls and limit what the program can do
provide the implementation of the interface. It dependencies implementations as possible. especially in the environment like web browsers
can have abstract and non-abstract methods. The intention of using this language is to give relief and mobile applications.
2. boolean: Java boolean keyword is used to to the developers from writing codes for every ➤ Robust: Java is strong. Java is robust because: It
declare a variable as a boolean type. platform. uses strong memory management.
It can hold True and False values only. The Java language is known for its robustness, . There is a lack of pointers that avoids security
3. break: Java break keyword is used to break the security, and simplicity features. problems.
loop or switch statement. It breaks the current Java provides automatic garbage collection which
FEATURES OF JAVA
flow of the program at specified conditions. runs on the Java Virtual Machine to get rid of
➤ Simple: Java is very easy to learn, and its syntax
4. byte: Java byte keyword is used to declare a objects which are not being used by a Java
is simple, clean and easy to understand.
variable that can hold 8-bit data values. application anymore.
➤Object-oriented: Java is an object-oriented
5. case: Java case keyword is used with the ➤Architecture-natural: Java is architecture natural
programming language. Everything in Java is an
switch statements to mark blocks of text. because there are no implementation dependent
object. Object-oriented means we organize our
6. catch: Java catch keyword is used to catch the features, for example, the size of primitive types is
software as a combination of different types of
fixed.
exceptions generated by try statements. It must objects that incorporate both data and behaviour.
be used after the try block only. ➤ Platform independent: Java is platform
7. float: Java float keyword is used to declare a independent because it is different from other Adapter Classes
variable that can hold a 32-bit floating- point languages like C, C++, etc. which are compiled into The adapter class can simplify n simplify the
number. platform specific machines while Java is a write creation of event handlers in certain situations.
8. for: Java for keyword is used to start a for once, run anywhere language. A platform is the An adapter class provides an empty
loop. It is used to execute a set of hardware or software environment in which a implementation of all methods in an event listener
instructions/functions repeatedly when some program runs. interface.
condition becomes true. If the number of ➤ Secured: Java is best known for its security. With Adapter classes are useful when you want to
iteration is fixed, it is recommended to use for Java, we can develop virus-free systems. Java is receive and process only some of the events that
secured because: No explicit pointer and Java are handled by a particular event listener interface.
loop.

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.

Simple if statement: Loop Statements 3. Java do-while loop


It is the most basic statement among all control 1. for loop ฀ The do-while loop checks the condition at the
flow statements in Java. It evaluates a Boolean 2. while loop end of the loop after executing the
expression and enables the program to enter a 3. do-while loop loop statements.
block of code if the expression evaluates to true. 1. Java for loop ฀ When the number of iteration is not known and
Syntax: if(condition) In Java, for loop is similar to C and C++. It enables we have to execute the loop at
statement 1;//xecutes when condition is true } us to initialize the loop variable, least once, we can use do-while loop.
if-else statement check the condition, and increment/decrement in a ฀ It is also known as the exit-controlled loop since
The if-else statement is an extension to the if- single line of code. We use for the condition is not checked in
statement, which uses another block of code, i.e., loop only when we exactly know the number of advance.
else block. The else block is executed if the times, we want to execute the block do
condition of the if-block is evaluated as false. of code. { //statements
if-else-if ladder: Syntax: } while (condition);
The if-else-if statement contains the if-statement for(initialization, condition, increment/decrement)
followed by multiple else-if statements. In other { Java break statement
words, we can say that it is the chain of if-else ฀ The break statement is used to break the current
2. Java for each loop
statements that create a decision tree where the flow of the program and
฀ Enhanced for loop it is used since jdk15.
program may enter in the block of code where the transfer the control to the next statement outside
฀ Used to process elements of array.
condition is true. a loop or switch statement
฀ Iterate elements without bounds.
Switch Statement: ฀ It breaks only the inner loop in the case of the
฀ Used to access array elements quickly without
In Java, Switch statements are similar to if-else-if nested loop.
performing initialization, testing
statements. The switch statement contains ฀ The break statement cannot be used
or increment or decrement
multiple blocks of code called cases and a single independently in the Java program, i.e,
Syntax:
case is executed based on the variable which is it can only be written inside the loop or switch
for(datatype identifier: arrayname)
being switched. The switch statement is easier to statement.
{
use instead of if-else-if statements. It also ฀ The break statement has two forms: labelled
//stmnts;
enhances the readability of the program. break and unlabeled break.
}
Java Arrays Interfaces in Java Types of Java Exceptions
Arrays are used to store multiple values in a single Definition of Interface in Java: There are mainly two types of exceptions: checked
variable, instead of declaring separate variables for An interface in Java is a reference type, similar to a and unchecked. An error is considered as the
each value. class, but it can contain only abstract methods unchecked exception. However, according to
Java array is an object which contains elements of (without a body) and constants (static final Oracle, there are three types of exceptions
a similar data type. Additionally, The elements of variables). Interfaces are used to achieve namely:
an array are stored in a contiguous memory abstraction and multiple inheritance in Java. A 1. Checked Exception
location. class that implements an interface must provide 2. Unchecked Exception
It is a data structure where we store similar an implementation for all the methods declared in 3. Error
elements. We can store only a fixed set of elements the interface. 1) Checked Exception
in a Java array. The classes that directly inherit the Throwable
What is Exception Handling? class except RuntimeException and Error are
ABSTRACT CLASS Exception Handling is a mechanism to handle known as checked exceptions. For example,
A class which is declared as abstract is known as an runtime errors such as ClassNotFoundException, IOException, SQLException, etc. Checked
abstract class. IOException, SQLException, RemoteException, etc. exceptions are checked at compile-time.
It can have abstract and non-abstract methods. Exception Handling in Java is a way to handle 2) Unchecked Exception
It needs to be extended and its method errors or unexpected situations that occur while a The classes that inherit the RuntimeException are
implemented. It cannot be instantiated. program is running, without crashing the program. known as unchecked exceptions. For example,
Rules for Abstract class:- Exception is an error that happens during program ArithmeticException, NullPointerException,
An abstract class must be declared with an execution (example: divide by zero, file not found, ArrayIndexOutOfBoundsException, etc.
abstract keyword. etc.) Unchecked exceptions are not checked at
It can have abstract and non-abstract methods. Handling is writing code to respond to that error compile-time, but they are checked at runtime.
It cannot be instantiated. properly. 3) Error
It can have constructors and static methods also
Error is irrecoverable. Some example of errors are
AR It can have final methods which will force the
OutOfMemoryError, Virtual Machine Error,
subclass not to change the body of the method.
AssertionError etc.

Java Input/Output InputStream Class Java Threads


Java I/O (Input and Output) is used to process the The InputStream class provides methods to read A Thread is a very light-weighted process.
input and produce the output. bytes from a file, console or memory. It is an - the smallest part of the process that allows a
Java uses the concept of a stream to make I/O abstract class and can't be instantiated; however, program to operate more efficiently by running
operation fast. The [Link] package contains all the various classes inherit the InputStream class and multiple tasks simultaneously.
classes required for input and output operations. override its methods. In order to perform complicated tasks in the
Stream background, we used the Thread concept in Java.
OutputStream Class
A stream is a sequence of data. In Java, a stream is - Lightweight process.
The OutputStream is an abstract class that is used
composed of bytes. It's called a stream because it → Series of executed statements.
to write 8-bit bytes to the stream. It is the
is like a stream of water that continues to flow. -Nested sequence of method calls.
superclass of all the output stream classes. This
A stream can be defined as a sequence of data. Life cycle of thread
class can't be instantiated; however, it is inherited
There are two kinds of Streams: 1) New (Ready to run)
by various subclasses that are given in the
InputStream - The InputStream is used to read A thread is in New when it gets CPU time.
following table.
data from a source. 2) Running
OutPutStream - The OutputStream is used for A thread is in a Running state when it is under
Synchronization in Java
writing data to a destination. execution
Synchronization in Java is the capability to control
3) Suspended
ByteStream Classes in Java the access of multiple threads to any shared
A thread is in the Suspended state when it is
ByteStream classes are used to read bytes from resource.
temporarily inactive or under execution.
the input stream and write bytes to the output Java Synchronization is better option where we
4) Blocked
stream. In other words, we can say that want to allow only one thread to access the shared
A thread is in the Blocked state when it is waiting
ByteStream classes read/write the data of 8-bits. resource.
for resources.
We can store video, audio, characters, etc., by Synchronization in java is used to remove the data
5) Terminated
using ByteStream classes. These classes are part of inconsistency when multiple threads access the
A thread comes in this state when at any given
the [Link] package. same object or resource simultaneously.
time, it halts its execution immediately.
The ByteStream classes are divided into two types
of classes, i.e., InputStream and OutputStream.

Java File Class Write to a File Introduction to JDBC (Java Database


Java File class represents the files and directory The next operation which we can perform on a file Connectivity)
pathnames in an abstract manner. This class is is "writing into a file". In order to write data into a What is JDBC?
used for creation of files and directories, file file, we will use the FileWriter class and its write() JDBC or Java Database Connectivity is a
searching, file deletion, etc. method together. We need to close the stream specification from Sun microsystems that provides
The File object represents the actual file/directory using the close() method to retrieve the allocated a standard abstraction (that is API or Protocol) for
on the disk. resources. java applications to communicate with various
File Operations Read from a File databases. It provides the language with java
We can perform the following operation on a file: The next operation which we can perform on a file database connectivity standard. It is used to write
Create a File is "read from a file". In order to write data into a programs required to access databases. JDBC
Get File Information file, we will use the Scanner class. Here, we need to along with the database driver is capable of
Write to a File close the stream using the close() method. We will accessing databases and spreadsheets.
Read from a File create an instance of the Scanner class and use interact with databases. It allows JDBC is a Java
Delete a File the hasNextLine() method nextLine() method to API that enables Java applications to connect and
Create a File get data from the file. intera you to:
Create a File operation is performed to create a Establish a connection to a database.
Delete a File
new file. We use the createNewFile() method of file. Send SQL statements (like SELECT, INSERT,
The next operation which we can perform on a file
The createNewFile() method returns true when it UPDATE, DELETE).
is "deleting a file". In order to delete a file, we will
successfully creates a new file and returns false Retrieve and process results from queries.
use the delete() method of the file. We don't need
when the file already exists. to close the stream using the close() method
Get File Information because for deleting a file, we neither use the
The operation is performed to get the file FileWriter class nor the Scanner class.
information. We use several methods to get the
information. about the file like name, absolute
path, is readable, is writable and length.
JDBC Architecture Types of JDBC Architecture Introduction to GUI Applications
The JDBC API supports both two-tier and three- The JDBC architecture consists of two-tier and What is GUI?
tier processing models access but in general, three-tier processing models to access a database. A GUI, or Graphical User Interface, in Java refers to
JDBC Architecture consists of two layers They are as described below: a way for users to interact with Java applications
databas 1. Two-tier model: A java application through visual elements like windows, buttons,
JDBC API: This provides the application-to-JDBC communicates directly to the data source. The and menus, rather than typing commands.
Manager connection. JDBC driver enables the communication between Basic Components of a GUI
JDBC Driver API: This supports the JDBC the application and the data source. When a user Pointer: It is a symbol that appears on the display
Manager-to-Driver Connection. sends a query to the data source, the answers for screen. It can be moved to select commands and
The JDBC API uses a driver manager and those queries are sent back to the user in the form objects
database-specific drivers to provide transparent of results. The data source can be located on a Pointing device: It allows you move the pointer
connectivity to heterogeneous databases. different machine on a network to which a user is and select objects on the screen, e.g. mouse or
The JDBC driver manager ensures that the correct connected. This is known as a client/server trackball.
driver is used to access each data source. configuration, where the user's machine acts as a Icons: It refers to small images on the display
The driver manager is capable of supporting client and the machine having the data source screen that represent commands, files, windows
multiple concurrent drivers connected to multiple running acts as the server. etc. Using pointer and pointing device, you can
heterogeneous databases. 2. Three -tier model: In this, the user's queries are execute these commands.
Following is the architectural diagram, which sent to middle-tier services, from which the Desktop: It is the display screen that contains the
shows the location of the driver manager with commands are again sent to the data source. The icons.
respect to the JDBC drivers and the Java results are sent back to the middle tier, and from
application there to the user. This type of model is found very
useful by management information system
directors.

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.

You might also like