You are on page 1of 22

UNIT-II

Basic Concepts of Object-Oriented Programming

Object-oriented programming is an approach that provides a way of modularizing programs by creating


partitioned memory area for both data and functions that can be used as templates for creating copies of
such modules on demand. This means that an object is considered to be a partitioned area of computer
memory that stores data and a set of operations that can access the data. Since the memory partitions are
independent, the objects can be used in a variety of different programs without modifications.

Objects and Classes

Objects are the basic runtime entities in an object-oriented system. They may represent a person, a place,
a bank account, a table of data or any item that the program may handle. They may also represent user-
defined data types such as vectors and lists. Any programming problem is analyzed in terms of objects
and the nature of communication between them.

When a program is executed, the objects interact by sending messages to one another. For example,
‘customer’ and ‘account’ are two objects in a banking program, then the customer object may send a
message to the account object requesting for the balance. Each object contains data and code to
manipulate the data. Objects can interact without having to know the details of each other's data or code.
It is sufficient to know the type of message accepted and the type of response returned by the objects.

Representation of an object

The entire set of data and code of an object can be made a user-defined data type using the concept of a
class. A class may be thought of as a 'data type' and an object as a 'variable' of that data type. Once a class
has been defined, we can create any number of objects belonging to that class. Each object is associated
with the data of type class with which they are created. A class is thus a collection of objects of similar
type.

Data Abstraction and Encapsulation

The wrapping up of data and methods into a single unit (called class) is known as encapsulation. Data
encapsulation is the most striking feature of a class. The data is not accessible to the outside world and
only those methods, which are wrapped in the class, can access it. These methods provide the interface
between the object's data and the program. This insulation of the data from direct access by the program
is called data hiding.

Abstraction refers to the act of representing essential features without including the background details or
explanations. Classes use the concept of abstraction and are defined as a list of abstract attributes such as
1
size, weight and cost, and methods that operate on these attributes. They encapsulate all the essential
properties of the objects that are to be created.
Inheritance

Inheritance is the process by which objects of one class acquire the properties of objects of another class.
Inheritance supports the concept of hierarchical classification. For example, the bird robin is a part of the
class flying bird, which is again a part of the class bird. The principle behind this sort of division is that
each derived class shares common characteristics with the class from which it is derived.

Property inheritance

In OOP, the concept of inheritance provides the idea of reusability. This means that we can add additional
features to an existing class without modifying it. This is possible by deriving a new class from the
existing one. The new class will have the combined features of both the classes. Thus the real appeal and
power of the inheritance mechanism is that it allows the programmer to reuse a class that is almost, but
not exactly. In Java, the derived class is known as 'subclass'.
Polymorphism
Polymorphism is another important OOP concept Polymorphism means the ability to take more than one
form. For example, an operation may exhibit different behavior in different instances. The behavior
depends upon the types of data used in the operation. For example, consider the operation of addition. For
two numbers, the operation will generate a sum. If the operands arc stings, then the operation would
produce a third sting by concatenation. A single function name can be used to handle different number
and different types of arguments.

Dynamic Binding

Binding refers to the linking of a procedure call to the code to be executed in response to the call.
2
Dynamic binding means that the code associated with a given procedure call is not known until the time
of the call at runtime. It is associated with polymorphism and inheritance. A procedure call associated
with a polymorphic reference depends on the dynamic type of that reference.

Message Communication

An object-oriented program consists of a set of objects that communicate with each other. The process of
programming in an object-oriented language, therefore, involves the following basic steps:
1. Creating classes that define objects and their behaviour.
2. Creating objects from class definitions.
3. Establishing communication among objects.

Objects communicate with one another by sending and receiving information much the same way as
people pass messages to one another.

Network of objects communicating between them

A message for an object is a request for execution of a procedure, and therefore will invoke a method
(procedure) in the receiving object that generates the desired result.

Message triggers a method

Message passing involves specifying the name of the object, the name of the method (message) and the
information to be sent. For example, consider the statement

Employee.salary(name);

Here, Employee is the object, salary is the message and name is the parameter that contains information.

1.4 Benefits of OOP

3
• Through inheritance, we can eliminate redundant code and extend the use of existing classes.
• We can build programs from the standard working modules that communicate with one another, rather
than having to stat writing the code from scratch. This leads to saving of development time and higher
productivity.
• The principle of data hiding helps the programmer to build secure programs that cannot be invaded by
code in other parts of the program.
• It is possible to have multiple objects to coexist without any interference.
• It is possible to map objects in the problem domain to those objects in the program.
• It is easy to partition the work in a project based on objects.
• The data-centered design approach enables us to capture more details of a model in an
implementable form.
• Object-oriented systems can be easily upgraded from small to large systems.
• Message passing techniques for communication between objects make the interface descriptions with
external systems much simpler.
• Software complexity can be easily managed.

1.5 Applications of OOP

Real-business systems are often much more complex and contain many more objects with complicated
attributes and methods. OOP is useful in this type of applications because it can simplify a complex
problem. The promising areas for application of OOP includes:

• Real-time systems
• Simulation and modelling
• Object-oriented databases
• Hypertext, hypermedia and expertext
• AI and expert systems
• Neural networks and parallel programming
• Decision support and office automation systems
• CAM/CAD system

It is believed that the richness of OOP environment will enable the software industry to improve not only
the quality of software systems but also its productivity.

Java Buzzwords

• Compiled and Interpreted


• Platform-Independent and Portable
• Object-Oriented
• Robust and Secure
• Distributed
• Familiar, Simple and Small
• Multithreaded and Interactive
• High Performance
• Dynamic and Extensible

Compiled and Interpreted

Usually a computer language is either compiled or interpreted. Java combines both these approaches thus
making Java a two-stage system. First, Java compiler translates source code into what is known as
bytecode instructions. Bytecodes are not machine instructions and therefore, in the second stage. Java
interpreter generates machine code that can be directly executed by the machine that is running the Java
program. We can thus say that Java is both a compiled and an interpreted language.

4
Platform-Independent and Portable

The most significant contribution of Java over other languages is its portability. Java programs can be
easily moved from one computer system to another, anywhere and anytime. Changes and upgrades in
operating systems, processors and system resources will not force any changes in Java programs. This is
the reason why Java has become a popular language for programming on Internet which interconnects
different kinds of systems worldwide. We can download a Java applet from a remote computer onto our
local system via Internet and execute it locally.

Object-Oriented

Java is a true object-oriented language. Almost everything in Java is an object. All program code and data
reside within objects and classes. Java comes with an extensive set of classes, arranged in packages, that
we can use in our programs by inheritance.

Robust and Secure

Java is a robust language. It provides many safeguards to ensure reliable code. It has strict compile time
and run time checking for data types. It is designed as a garbage-collected language relieving the
programmers virtually all memory management problems. Java also incorporates the concept of
exception handling which captures series errors and eliminates any risk of crashing the system.

Security becomes an important issue for a language that is used for programming on Internet. Threat of
viruses and abuse of resources are everywhere. Java systems not only verify all memory access but also
ensure that no viruses are communicated with an applet. The absence of pointers in Java ensures that
programs cannot gain access to memory locations without proper authorization.

Distributed

Java is designed as a distributed language for creating applications on networks. It has the ability to share
both data and programs. Java applications can open and access remote objects on Internet as easily as
they can do in a local system. This enables multiple programmers at multiple remote locations to
collaborate and work together on a single project.

Simple, Small and Familiar

Java is a small and simple language. Many features of C and C++ that are either redundant or sources of
unreliable code are not part of Java. For example, Java does not use pointers, preprocessor header files,
goto statement and many others. It also eliminates operator overloading and multiple inheritance.

Familiarity is another striking feature of Java. To make the language look familiar to the existing
programmers, it was modelled on C and C++ languages. Java uses many constructs of C and C++ and
therefore. Java code "looks like a C++" code. In fact, Java is a simplified version of C++.

Multithreaded and Interactive

Multithreaded means handling multiple tasks simultaneously. Java supports multithreaded programs. This
means that we need not wait for the application to finish one task before beginning another. For example,
we can listen to an audio clip while scrolling a page and at the same time download an applet from a
distant computer.

The Java runtime comes with tools that support multiprocess synchronization and construct smoothly
running interactive systems.

5
High Performance

Java performance is impressive for an interpreted language, mainly due to the use of intermediate
bytecode. According to Sun, Java speed is comparable to the native C/C++. Java architecture is also
designed to reduce overheads during runtime. Further, the incorporation of multireading enhances the
overall execution speed of Java programs.

Dynamic and Extensible

Java is a dynamic language. Java is capable of dynamically linking in new class libraries, methods, and
objects. Java can also determine the type of class through a query, making it possible to either
dynamically link or abort the program, depending on the response.

Java programs support functions written in other languages such as C and C++. These functions are
known as native methods. This facility enables the programmers to use the efficient functions available in
these languages. Native methods are linked dynamically at runtime.

Dynamic Binding
Binding means an association of method call to the method definition. The picture below clearly shows
what is binding. There are two types of Binding: Static and Dynamic Binding in Java.
If the compiler maps the method at compile-time, it is Static Binding or early binding. And, if the method
is resolved at runtime, it is Dynamic Binding or late binding.

Static Binding or Early Binding in Java


• Static Binding or Early Binding in Java refers to a process where the compiler determines the type
of object and resolves the method during the compile-time. Generally, the compiler binds the
overloaded methods using static binding.
• There is a fact that the binding of static, private, and final methods are always done during
compile-time using static-binding.
• Why is the binding of static, final and private methods always a static binding?
• The reason for the binding of private, final and static methods during the compile-time is that the
compiler determines the type of the class at the compile-time and therefore we cannot override
them during the runtime.
• Another reason is that the static binding of methods provides better performance than the runtime
binding. The compiler becomes aware of these methods and understands that method overriding is
not possible with such methods.
• These methods can only be accessed by the object of the local class. Therefore the binding of
these methods always takes place during compilation.
Example of Static Binding in Java
Suppose we have two classes named Person and Teacher. The Teacher class extends the Person class.
Both of these classes have the same methods called speak(). But, this method is static so we cannot
override it. Therefore, even if we use the object of the Teacher class then also it calls the method of the
Person class.

Code to understand the static binding in Java


package com.techvidvan.binding;
class Person
{
public void speak()
{
System.out.println("Person speaks");
}
}
class Teacher extends Person
6
{
public static void speak()
{
System.out.println("Teacher speaks");
}
}
public class StaticBinding
{
public static void main( String args[ ])
{
// Reference is of Person type and object is Teacher type
Person obj = new Teacher();
obj.speak();
//Reference and object both are of Person type.
Person obj2 = new Person();
obj2.speak();
}
}
Dynamic Binding or Late Binding in Java
• When the compiler resolves the method call binding during the execution of the program, such a
process is known as Dynamic or Late Binding in Java. We also call Dynamic binding as Late
Binding because binding takes place during the actual execution of the program.
• The best example of Dynamic binding is the Method Overriding where both the Parent class and
the derived classes have the same method. And, therefore the type of the object determines which
method is going to be executed.
• The type of object is determined during the execution of the program, therefore it is called
dynamic binding.
Example of Dynamic Binding in Java
We consider the same example that we took in the static binding. But this code differs from the above
code and gives the different output as the actual method overriding is happening here.
The actual overriding takes place since the methods are not declared as static, private, and final. Let’s see
an example to understand this:
Code to understand the Dynamic Binding in Java:
package com.techvidvan.binding
class Person
{
public void speak()
{
System.out.println("Person speaks");
}
}
class Teacher extends Person
{
@Override
public void speak()
{
System.out.println("Teacher speaks");
}
}
public class DynamicBinding
{
public static void main( String args[])
{
//Reference and objects are of Person type.
7
Person obj2 = new Person();
obj2.speak();
// Reference is of Person type and object is Teacher type
Person obj = new Teacher();
obj.speak();
}
}

Differences between Static Binding and Dynamic Binding


S.N. Static Binding Dynamic Binding
A type of polymorphism that collects the
A type of polymorphism that collects the
1. information to call a method during the
information to call a method at the runtime.
compile-time.
2. The binding happens at compile time. The binding happens at runtime.
3. The actual object is not used for binding. The actual object is used for binding.
It is also called early binding because binding It is also called late binding because binding
4.
happens during compilation. happens at run time.
5. The execution speed is high. The execution speed is slow.
Method overloading is the best example of Method overriding is the best example of
6.
static binding. dynamic binding.
The methods which are private, static and final, The methods other private, static and final methods show
7. show static binding because we cannot override dynamic binding because overriding is possible with
them. these methods.

Abstract Classes and Methods


Data abstraction is the process of hiding certain details and showing only essential information to the
user. Abstraction can be achieved with either abstract classes or interfaces (which you will learn more
about in the next chapter).
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).
An abstract class can have both abstract and regular methods:
abstract class Animal {
public abstract void animalSound();
public void sleep() {
System.out.println("Zzz");
}
}

From the example above, it is not possible to create an object of the Animal class:
Animal myObj = new Animal(); // will generate an error
To access the abstract class, it must be inherited from another class.
Example
// Abstract class
abstract class Animal {
8
// Abstract method (does not have a body)
public abstract void animalSound();
// Regular method
public void sleep() {
System.out.println("Zzz");
}
}
// Subclass (inherit from Animal)
class Pig extends Animal {
public void animalSound() {
// The body of animalSound() is provided here
System.out.println("The pig says: wee wee");
}
}

class Main {
public static void main(String[] args) {
Pig myPig = new Pig(); // Create a Pig object
myPig.animalSound();
myPig.sleep();
}
}
Interfaces
Another way to achieve abstraction in Java is with interfaces.
An interface is a completely "abstract class" that is used to group related methods with empty bodies:
Example
// interface
interface Animal {
public void animalSound(); // interface method (does not have a body)
public void run(); // interface method (does not have a body)
}

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:
Example
// Interface
interface Animal {
public void animalSound(); // interface method (does not have a body)
public void sleep(); // interface method (does not have a body)
}

// Pig "implements" the Animal interface


class Pig implements Animal {
public void animalSound() {
// The body of animalSound() is provided here
System.out.println("The pig says: wee wee");
}
public void sleep() {
// The body of sleep() is provided here
System.out.println("Zzz");
}
}
class Main {

9
public static void main(String[] args) {
Pig myPig = new Pig(); // Create a Pig object
myPig.animalSound();
myPig.sleep();
}
}

Notes on Interfaces:
• Like abstract classes, interfaces cannot be used to create objects (in the example above, it is not
possible to create an "Animal" object in the MyMainClass)
• Interface methods do not have a body - the body is provided by the "implement" class
• On implementation of an interface, you must override all of its methods
• Interface methods are by default abstract and public
• Interface attributes are by default public, static and final
• An interface cannot contain a constructor (as it cannot be used to create objects)
Why And When To Use Interfaces?
1) To achieve security - hide certain details and only show the important details of an object (interface).
2) Java does not support "multiple inheritance" (a class can only inherit from one superclass). However, it
can be achieved with interfaces, because the class can implement multiple interfaces. Note: To
implement multiple interfaces, separate them with a comma (see example below).

Multiple Interfaces
To implement multiple interfaces, separate them with a comma:
Example
interface FirstInterface {
public void myMethod(); // interface method
}

interface SecondInterface {
public void myOtherMethod(); // interface method
}

class DemoClass implements FirstInterface, SecondInterface {


public void myMethod() {
System.out.println("Some text..");
}
public void myOtherMethod() {
System.out.println("Some other text...");
}
}

class Main {
public static void main(String[] args) {
DemoClass myObj = new DemoClass();
myObj.myMethod();
myObj.myOtherMethod();
}}
Packages
A java package is a group of similar types of classes, interfaces and sub-packages.
Package in java can be categorized in two form, built-in package and user-defined package.
There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
Here, we will have the detailed learning of creating and using user-defined packages.
Keep Watching

10
Advantage of Java Package
1) Java package is used to categorize the classes and interfaces so that they can be easily maintained.
2) Java package provides access protection.
3) Java package removes naming collision.

Simple example of java package


The package keyword is used to create a package in java.
//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
How to compile java package
If you are not using any IDE, you need to follow the syntax given below:
javac -d directory javafilename
For example
javac -d . Simple.java
The -d switch specifies the destination where to put the generated class file. You can use any directory
name like /home (in case of Linux), d:/abc (in case of windows) etc. If you want to keep the package
within the same directory, you can use . (dot).
How to run java package program
You need to use fully qualified name e.g. mypack.Simple etc to run the class.
To Compile: javac -d . Simple.java
To Run: java mypack.Simple
The -d is a switch that tells the compiler where to put the class file i.e. it represents destination.
The . represents the current folder.
How to access package from another package?
There are three ways to access the package from outside the package.
1. import package.*;
2. import package.classname;
3. fully qualified name.
1) Using packagename.*
If you use package.* then all the classes and interfaces of this package will be accessible
but not subpackages.
The import keyword is used to make the classes and interface of another package accessible
11
to the current package.
Example of package that import the packagename.*
1. //save by A.java
2. package pack;
3. public class A{
4. public void msg(){System.out.println("Hello");}
5. }

//save by B.java
1. package mypack;
2. import pack.*;
3. class B{
4. public static void main(String args[]){
5. A obj = new A();
6. obj.msg();
7. }
8. }
2) Using packagename.classname
If you import package.classname then only declared class of this package will be accessible.
Example of package by import package.classname
1. //save by A.java
2.
3. package pack;
4. public class A{
5. public void msg(){System.out.println("Hello");}
6. }
//save by B.java
1. package mypack;
2. import pack.A;
3. class B{
4. public static void main(String args[]){
5. A obj = new A();
6. obj.msg();
7. }
8. }
3) Using fully qualified name
If you use fully qualified name then only declared class of this package will be accessible. Now
there is no need to import. But you need to use fully qualified name every time when you are
accessing the class or interface.
It is generally used when two packages have same class name e.g. java.util and java.sql
packages contain Date class.
Example of package by import fully qualified name
1. //save by A.java
2. package pack;
3. public class A{
4. public void msg(){System.out.println("Hello");}
5. }
//save by B.java
1. package mypack;
2. class B{
3. public static void main(String args[]){
4. pack.A obj = new pack.A();//using fully qualified name
5. obj.msg();
6. }
12
7. }
GUI Programming with Java
Event
Change in the state of an object is known as event i.e. event describes the change in state
of source. Events are generated as result of user interaction with the graphical user
interface components. For example, clicking on a button, moving the mouse, entering a
character through keyboard, selecting an item from list, scrolling the page are the
activities that causes an event to happen.
Types of Event
The events can be broadly classified into two categories:
• Foreground Events - Those events which require the direct interaction of user.
They are generated as consequences of a person interacting with the graphical
components in Graphical User Interface. For example, clicking on a button,
moving the mouse, entering a character through keyboard, selecting an item from
list, scrolling the page etc.
• Background Events - Those events that require the interaction of end user are
known as background events. Operating system interrupts, hardware or software
failure, timer expires, an operation completion are the example of background
events.
Event Handling
Event Handling is the mechanism that controls the event and decides what should happen
if an event occurs. This mechanism have the code which is known as event handler that is
executed when an event occurs. Java Uses the Delegation Event Model to handle the
events. This model defines the standard mechanism to generate and handle the events.
Let's have a brief introduction to this model.
The Delegation Event Model has the following key participants namely:
• Source - The source is an object on which event occurs. Source is responsible for
providing information of the occurred event to it's handler. Java provide as with
classes for source object.
• Listener - It is also known as event handler. Listener is responsible for generating
response to an event. From java implementation point of view the listener is also an
object. Listener waits until it receives an event. Once the event is received , the
listener process the event an then returns.
The benefit of this approach is that the user interface logic is completely separated from
the logic that generates the event. The user interface element is able to delegate the
processing of an event to the separate piece of code. In this model ,Listener needs to be
registered with the source object so that the listener can receive the event notification.
This is an efficient way of handling the event because the event notifications are sent only
to those listener that want to receive them.

13
Java Event classes and Listener interfaces
Event Classes Listener Interfaces

ActionEvent ActionListener

MouseEvent MouseListener and MouseMotionListener

MouseWheelEvent MouseWheelListener

KeyEvent KeyListener

ItemEvent ItemListener

TextEvent TextListener

AdjustmentEvent AdjustmentListener

WindowEvent WindowListener

ComponentEvent ComponentListener

ContainerEvent ContainerListener

FocusEvent FocusListener

Registration Methods

For registering the component with the Listener, many classes provide the registration
methods. For example:

o Button
o public void addActionListener(ActionListener a){}
o MenuItem
o public void addActionListener(ActionListener a){}
o TextField
o public void addActionListener(ActionListener a){}
o public void addTextListener(TextListener a){}
o TextArea
o public void addTextListener(TextListener a){}
o Checkbox
o public void addItemListener(ItemListener a){}
o Choice
o public void addItemListener(ItemListener a){}

14
o List
o public void addActionListener(ActionListener a){}
o public void addItemListener(ItemListener a){}

Steps involved in event handling


• The User clicks the button and the event is generated.
• Now the object of concerned event class is created automatically and information
about the source and the event get populated with in same object.
• Event object is forwarded to the method of registered listener class.
• the method is now get executed and returns.
Event Handling Example
import java.awt.*;
import java.awt.event.*;
class AEvent extends Frame implements ActionListener{
TextField tf;
AEvent(){

//create components
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(100,120,80,30);

//register listener
b.addActionListener(this);//passing current instance

//add components and set size, layout and visibility


add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
tf.setText("Welcome");
}
public static void main(String args[]){
new AEvent();
}

15
}

Note:public void setBounds(int xaxis, int yaxis, int width, int height); have been used
in the above example that sets the position of the component it may be button, textfield
etc.

Applets

Applets arc small Java programs that are primarily used in Internet computing. They can be
transported over the Internet from one computer to another and run using the Applet Viewer or
any Web browser that supports Java. An applet, like any application program, can do many
things for us. It can perform arithmetic operations, display graphics, play sounds, accept user
input, create animation, and play interactive games.

How Applets Differ from Applications

Although both the applets and stand-alone applications are Java programs, there arc
significant differences between them. Applets arc not full-featured application programs. They
arc usually written to accomplish a small task or a component of a task. Since they arc
usually designed for use on the Internet, they impose certain limitations and restrictions in
their design.

• Applets do not use the main( ) method for initiating the execution of the code.
Applets, when loaded, automatically call certain methods of Applet class to start and
execute the applet code. e Unlike stand-alone applications, applets cannot be run
independently. They are run from inside a Web page using a special feature known as
HTML tag.
• Applets cannot read from or write to the files in the local computer.
• Applets cannot communicate with other servers on the network.
• Applets cannot run any program from the local computer.
• Applets arc restricted from using libraries from other languages such as C or C+ •*-.
(Remember, Java language supports this feature through native methods).
The steps invoked in developing and testing in applet arc:
1. Building an applet code (.Java ile)
2. Creating an executable applet (.class ile)
3. Designing a Web page using HTML tags
4. Preparing <APPLET> tag
5.Incorporating <APPI.F.T> tag into the Web page
6. Creating HTML ile
7. Testing the applet code

Lifecycle of Java Applet

1. Applet is initialized.
2. Applet is started.
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.

16
Lifecycle methods for Applet:

The java.applet.Applet class 4 life cycle methods and java.awt.Component class provides 1 life cycle
methods for an applet.

java.applet.Applet class

For creating any applet java.applet.Applet class must be inherited. It provides 4 life cycle methods of
applet.

1. public void init(): is used to initialized the Applet. It is invoked only once.
2. public void start(): is invoked after the init() method or browser is maximized. It is used to start
the Applet.
3. public void stop(): is used to stop the Applet. It is invoked when Applet is stop or browser is
minimized.
4. public void destroy(): is used to destroy the Applet. It is invoked only once.

java.awt.Component class

The Component class provides 1 life cycle method of applet.

public void paint(Graphics g): is used to paint the Applet. It provides Graphics class object that can be
used for drawing oval, rectangle, arc etc.

How to run an Applet?

There are two ways to run an applet

1. By html file.
2. By appletViewer tool (for testing purpose).

Simple example of Applet by html file:

To execute the applet by html file, create an applet and compile it. After that create an html file and place
the applet code in html file. Now click the html file.

//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{
public void paint(Graphics g){
g.drawString("welcome",150,150);
}
}

17
myapplet.html

<html>
<body>
<applet code="First.class" width="300" height="300">
</applet>
</body>
</html>

Simple example of Applet by appletviewer tool:

To execute the applet by appletviewer tool, create an applet that contains applet tag in comment and
compile it. After that run it by: appletviewer First.java. Now Html file is not required but it is for testing
purpose only.

//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{
public void paint(Graphics g){
g.drawString("welcome to applet",150,150);
}
}
/*
<applet code="First.class" width="300" height="300">
</applet>
*/

To execute the applet by appletviewer tool, write in command prompt:

c:\>javac First.java
c:\>appletviewer First.java

Java Swing

It is a part of Java Foundation Classes (JFC) that is used to create window-based applications. It is built
on the top of AWT (Abstract Windowing Toolkit) API and entirely written in java. Unlike AWT, Java
Swing provides platform-independent and lightweight components. The javax.swing package provides
classes for java swing API such as JButton, JTextField, JTextArea, JRadioButton, JCheckbox, JMenu,
JColorChooser etc.

Difference between AWT and Swing

There are many differences between java awt and swing that are given below.

18
No. Java AWT Java Swing

1) AWT components are platform-dependent. Java swing components


are platform-independent.

2) AWT components are heavyweight. Swing components are lightweight.

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

4) AWT provides less components than Swing. Swing provides more powerful
components such as tables, lists,
scrollpanes, colorchooser,
tabbedpane etc.

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


Controller) where model represents data, view
represents presentation and controller acts as an
interface between model and view.

MVC Architecture
Swing API architecture follows loosely based MVC architecture in the following manner.
• Model represents component's data.
• View represents visual representation of the component's data.
• Controller takes the input from the user on the view and reflects the changes in Component's data.
• Swing component has Model as a seperate element, while the View and Controller part are
clubbed in the User Interface elements. Because of which, Swing has a pluggable look-and-feel
architecture.

Hierarchy of Java Swing classes

19
Commonly used Methods of Component class

The methods of Component class are widely used in java swing that are given below.

Method Description

public void add(Component c) add a component on another component.

public void setSize(int width,int height) sets size of the component.

public void setLayout(LayoutManager m) sets the layout manager for the component.

public void setVisible(boolean b) sets the visibility of the component. It is by default false.

Java Swing Examples

There are two ways to create a frame:

o By creating the object of Frame class (association)


o By extending Frame class (inheritance)

We can write the code of swing inside the main(), constructor or any other method.

Simple Java Swing Example

Let's see a simple swing example where we are creating one button and adding it on the JFrame object
inside the main() method.

File: FirstSwingExample.java

import javax.swing.*;
public class FirstSwingExample {
public static void main(String[] args) {
JFrame f=new JFrame();//creating instance of JFrame
JButton b=new JButton("click");//creating instance of JButton
b.setBounds(130,100,100, 40);//x axis, y axis, width, height
f.add(b);//adding button in JFrame
f.setSize(400,500);//400 width and 500 height
f.setLayout(null);//using no layout managers
f.setVisible(true);//making the frame visible
}
}

20
The following are the important components of the Java Swing class.

JButton Class
The JButton Class within the Java swing components is the component useful to build a labeled button.
Moreover, this button has platform-independent execution. Further, when the button is pushed it makes
some action as a result and it also inherits the AbstractButton class. There are some commonly used
constructors of the JButton class such as JButton(), JButton (String S), and JButton (Icon i).

e.q :-JButton okBtn = new JButton(“Ok”);

JLabel
The JLabel class object within the swing component is useful for placing text in a container. Also, this
class is useful to present a single line of text in read-only. There is an option to change the text later by
an application but a user has no authority to edit directly. Also, the JLabel component inherits
JComponent class. The constructors that JLabel uses are the following types. Such as JLabel(), JLabel
(String S), (Icon i), and JLabel(String s, Icon I, int horizontal alignment).

e.g.:-JLabel textLbl = new JLabel(“This is a text label.”);

JTextField
The JTextField class object inherits the JTextComponent class and it allows the modification of a single
line of text.

e.q.:-JTextField txtBox = new JTextField(20);

JTextArea
The JTextArea class object includes multiple lines region that presents the text. Also, this component
takeovers the JTextComponent class and allows the modification of the multiple-line text. Here, the
constructors of this component include the following.-JTextArea(), JTextArea(int row, int column), etc.

e.q.:-JTextArea txtArea = new JTextArea(“This text is default


text for text area.”, 5, 20);

JList
The JComponent Class takeovers the JList Class where the JList Class represents the object of the list
of text items. Hence, the constructors that JList class includes the following as JList (), JList(ary[] list
data), etc.

e.q.:-

DefaultListItem cityList=newDefaultListItem();
cityList.addElement(“Mumbai”):
cityList.addElement(“London”):
cityList.addElement(“NewYork”):
cityList.addElement(“Sydney”):
cityList.addElement(“Tokyo”):
JList cities = new JList(cityList);
cities.setSelectionModel(ListSelectionModel.SINGLE_SELECTION);
21
JComboBox
The choice class is usful to present the popup of the menu of choices and it also takeovers the
JComponent class. Whatever choice the user selects it shows on the top of the menu.

The constructors of the JComboBox Class are as follows-JComboBox(), JComboBox(Object[] items),


etc.

e.g. :-String[] cityStrings = { "Mumbai", "London", "New


York", "Sydney", "Tokyo" };
JComboBox cities = new JComboBox(cityList);
cities.setSelectedIndex(3);

JCheckBox
This Java swing component is useful to build the checkbox. Also, it is useful to turn an option on or off
that represents true or false. The JCheckbox inherits the JToggleButton class and by clicking on the
check box it modifies the state of on/off options. This check box commonly uses the constructors such as
JJCheckBox(), JCheckBox(Action X), JCheckBox (String s), etc.

e.g. :-CheckBox chkBox = new JCheckBox(“Show Help”, true);

JRadioButton
JRadioButton is used to render a group of radio buttons in the UI. A user can select one choice from the
group.
e.g. :-
ButtonGroup radioGroup = new ButtonGroup();
JRadioButton rb1 = new JRadioButton(“Easy”, true);
JRadioButton rb2 = new JRadioButton(“Medium”);
JRadioButton rb3 = new JRadioButton(“Hard”);
radioGroup.add(rb1);
radioGroup.add(rb2);
radioGroup.add(rb3);

22

You might also like