Unit-Ii Basic Concepts of Object-Oriented Programming
Unit-Ii Basic Concepts of Object-Oriented Programming
Unit-Ii Basic Concepts of Object-Oriented Programming
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.
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.
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 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.
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.
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
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.
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.
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 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.
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.
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
8
abstract class Animal {
// 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)
}
9
class Main {
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 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.
11
to the current package.
Example of package that import the packagename.*
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
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
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.A;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
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
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
class B{
public static void main(String args[]){
pack.A obj = new pack.A();//using fully qualified name
obj.msg();
}
12
}
13
Java Event classes and Listener interfaces
Event Classes Listener Interfaces
ActionEvent ActionListener
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){}
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.
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
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
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.
1. By html file.
2. By appletViewer tool (for testing purpose).
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>
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>
*/
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.
There are many differences between java awt and swing that are given below.
18
No. Java AWT Java Swing
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.
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 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.
We can write the code of swing inside the main(), constructor or any other method.
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).
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).
JTextField
The JTextField class object inherits the JTextComponent class and it allows the modification of a single
line of text.
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.
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.
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.
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