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

CMP 325 Javatech Note

The document provides an overview of Java as both a programming language and platform. It describes Java as being simple, object-oriented, distributed, multithreaded, dynamic, architecture neutral, portable, high-performance, robust and secure. The design goals of Java were to develop software for heterogeneous distributed environments in a secure, portable and efficient way. Key features of Java include being architecture neutral through the use of bytecodes, automatic memory management, strong security features and support for multithreading.

Uploaded by

rexdum7
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views

CMP 325 Javatech Note

The document provides an overview of Java as both a programming language and platform. It describes Java as being simple, object-oriented, distributed, multithreaded, dynamic, architecture neutral, portable, high-performance, robust and secure. The design goals of Java were to develop software for heterogeneous distributed environments in a secure, portable and efficient way. Key features of Java include being architecture neutral through the use of bytecodes, automatic memory management, strong security features and support for multithreading.

Uploaded by

rexdum7
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 92

CMP 325

OBJECT-ORIENTED
PROGRAMMING - JAVA
About the Java Technology
Java technology is both a programming
language and a platform.

The Java Programming Language


The Java programming language is a
high-level language that can be
characterized by all of the following
buzzwords:
 Simple
 Object oriented
 Distributed
 Multithreaded
 Dynamic
 Architecture neutral
 Portable
 High performance
 Robust
 Secure
Beginnings of the Java TM Programming Language Project
The Java TM programming language is designed to meet the challenges of
application development in the context of heterogeneous, network-wide
distributed environments. Paramount among these challenges is secure
delivery of applications that consume the minimum of system resources,
can run on any hardware and software platform, and can be extended
dynamically.
The Java programming language originated as part of a research project
to develop advanced software for a wide variety of network devices and
embedded systems. The goal was to develop a small, reliable, portable,
distributed, real-time operating platform. When the project started, C++
was the language of choice. But over time the difficulties encountered
with C++ grew to the point where the problems could best be addressed
by creating an entirely new language platform. Design and architecture
decisions drew from a variety of languages such as Eiffel, SmallTalk,
Objective C, and Cedar/Mesa. The result is a language platform that has
proven ideal for developing secure, distributed, network-based end-user
applications in environments ranging from network-embedded devices to
the World-Wide Web and the desktop.
Design Goals of the Java TM Programming Language
The design requirements of the Java TM programming language
are driven by the nature of the computing environments in which
software must be deployed.
The massive growth of the Internet and the World-Wide Web
leads us to a completely new way of looking at development and
distribution of software. To live in the world of electronic
commerce and distribution, Java technology must enable the
development of secure, high performance, and
highly robust applications on multiple
platforms in heterogeneous, distributed networks.
Operating on multiple platforms in heterogeneous networks
invalidates the traditional schemes of binary distribution,
release, upgrade, patch, and so on. To survive in this jungle, the
Java programming language must be architecture
neutral, portable, and dynamically adaptable.
The system that emerged to meet these needs
is simple, so it can be easily programmed by most
developers; familiar, so that current developers can
easily learn the Java programming language; object
oriented, to take advantage of modern software
development methodologies and to fit into
distributed client-server applications; multithreaded,
for high performance in applications that need to
perform multiple concurrent activities, such as
multimedia; and interpreted, for maximum
portability and dynamic capabilities.
Together, the above requirements comprise quite a
collection of buzzwords, so let's examine some of
them and their respective benefits before going on.
Simple, Object Oriented, and Familiar
Primary characteristics of the Java programming language
include a simple language that can be programmed without
extensive programmer training while being attuned to current
software practices. The fundamental concepts of Java
technology are grasped quickly; programmers can be
productive from the very beginning.
The Java programming language is designed to be object
oriented from the ground up. Object technology has finally
found its way into the programming mainstream after a
gestation period of thirty years. The needs of distributed, client-
server based systems coincide with the encapsulated, message-
passing paradigms of object-based software. To function within
increasingly complex, network-based environments,
programming systems must adopt object-oriented concepts.
Java technology provides a clean and efficient object-based
development platform.
Programmers using the Java programming language can
access existing libraries of tested objects that provide
functionality, ranging from basic data types, through I/O
and network interfaces to graphical user interface
toolkits. These libraries can be extended to provide new
behaviour.
Even though C++ was rejected as an implementation
language, keeping the Java programming language
looking like C++ as far as possible results in it being
a familiar language, while removing the unnecessary
complexities of C++. Having the Java programming
language retain many of the object-oriented features and
the "look and feel" of C++ means that programmers can
migrate easily to the Java platform and be productive
quickly.
Robust and Secure
The Java programming language is designed for creating
highly reliable software. It provides extensive compile-time checking, followed
by a second level of run-time checking. Language features guide programmers
towards reliable programming habits.
The memory management model is extremely simple: objects are created
with a new operator. There are no explicit programmer-defined pointer data
types, no pointer arithmetic, and automatic garbage collection. This simple
memory management model eliminates entire classes of programming errors
that bedevil C and C++ programmers. You can develop Java code with
confidence that the system will find many errors quickly and that major
problems won't lay dormant until after your production code has shipped.
Java technology is designed to operate in distributed environments, which
means that security is of paramount importance. With security features
designed into the language and run-time system, Java technology lets you
construct applications that can't be invaded from outside. In the network
environment, applications written in the Java programming language are
secure from intrusion by unauthorized code attempting to get behind the
scenes and create viruses or invade file systems.
Architecture Neutral and Portable
Java technology is designed to support applications that will be
deployed into heterogeneous network environments. In such
environments, applications must be capable of executing on a
variety of hardware architectures. Within this variety of
hardware platforms, applications must execute atop a variety of
operating systems and interoperate with multiple programming
language interfaces. To accommodate the diversity of operating
environments, the Java Compiler TM product
generates bytecodes--an architecture neutral intermediate
format designed to transport code efficiently to multiple
hardware and software platforms. The interpreted nature of Java
technology solves both the binary distribution problem and the
version problem; the same Java programming language byte
codes will run on any platform.
Architecture neutrality is just one part of a truly portable system.
Java technology takes portability a stage further by being strict in its
definition of the basic language. Java technology puts a stake in the
ground and specifies the sizes of its basic data types and the
behaviour of its arithmetic operators. Your programs are the same on
every platform--there are no data type incompatibilities across
hardware and software architectures.
The architecture-neutral and portable language platform of Java
technology is known as the Java virtual machine. It's the specification
of an abstract machine for which Java programming language
compilers can generate code. Specific implementations of the Java
virtual machine for specific hardware and software platforms then
provide the concrete realization of the virtual machine. The Java
virtual machine is based primarily on the POSIX interface
specification--an industry-standard definition of a portable system
interface. Implementing the Java virtual machine on new
architectures is a relatively straightforward task as long as the target
platform meets basic requirements such as support for
High Performance
Performance is always a consideration. The Java platform
achieves superior performance by adopting a scheme by which
the interpreter can run at full speed without needing to check
the run-time environment. The automatic garbage
collector runs as a low-priority background thread, ensuring a
high probability that memory is available when required,
leading to better performance. Applications requiring large
amounts of compute power can be designed such that
compute-intensive sections can be rewritten in native machine
code as required and interfaced with the Java platform. In
general, users perceive that interactive applications respond
quickly even though they're interpreted.
Interpreted, Threaded, and Dynamic
The Java interpreter can execute Java bytecodes directly on any
machine to which the interpreter and run-time system have been
ported. In an interpreted platform such as Java technology-based
system, the link phase of a program is simple, incremental, and
lightweight. You benefit from much faster development cycles--
prototyping, experimentation, and rapid development are the normal
case, versus the traditional heavyweight compile, link, and test
cycles.
Modern network-based applications, such as the HotJava TM Browser
for the World Wide Web, typically need to do several things at the
same time. A user working with HotJava Browser can run several
animations concurrently while downloading an image and scrolling
the page. Java technology's multithreading capability provides the
means to build applications with many concurrent threads of activity.
Multithreading thus results in a high degree of interactivity for the
end user.
The Java platform supports multithreading at the language level with
the addition of sophisticated synchronization primitives: the language
library provides the Thread class, and the run-time system provides
monitor and condition lock primitives. At the library level, moreover,
Java technology's high-level system libraries have been written to
be thread safe: the functionality provided by the libraries is available
without conflict to multiple concurrent threads of execution.
While the Java Compiler is strict in its compile-time static checking, the
language and run-time system are dynamic in their linking stages.
Classes are linked only as needed. New code modules can be linked in on
demand from a variety of sources, even from sources across a network.
In the case of the HotJava Browser and similar applications, interactive
executable code can be loaded from anywhere, which enables
transparent updating of applications. The result is on-line services that
constantly evolve; they can remain innovative and fresh, draw more
customers, and spur the growth of electronic commerce on the Internet.
The Java Platform--a New Approach to Distributed Computing
Taken individually, the characteristics discussed above can be
found in a variety of software development platforms. What's
completely new is the manner in which Java technology and its
runtime environment have combined them to produce a flexible
and powerful programming system.
Developing your applications using the Java programming
language results in software that is portable across multiple
machine architectures, operating systems, and graphical user
interfaces, secure, and high performance. With Java
technology, your job as a software developer is much easier--
you focus your full attention on the end goal of shipping
innovative products on time, based on the solid foundation of
the Java platform. The better way to develop software is here,
now, brought to you by the Java platform.
In the Java programming language, all source
code is first written in plain text files ending
with the .java extension. Those source files
are then compiled into .class files by the
javac compiler. A .class file does not
contain code that is native to your processor; it
instead contains bytecodes — the machine
language of the Java Virtual Machine 1 (Java
VM). The java launcher tool then runs your
application with an instance of the Java Virtual
Machine.
An overview of the software development process.
Because the Java VM is available on many different
operating systems, the same .class files are capable
of running on Microsoft Windows, the Solaris™
Operating System (Solaris OS), Linux, or Mac OS.
Some virtual machines, such as the Java SE HotSpot
at a Glance, perform additional steps at runtime to give
your application a performance boost. This includes
various tasks such as finding performance bottlenecks
and recompiling (to native code) frequently used
sections of code.
Through the Java VM, the same application is capable of running on multiple
platforms.
The Java Platform
A platform is the hardware or software environment in which
a program runs. We've already mentioned some of the most
popular platforms like Microsoft Windows, Linux, Solaris
OS, and Mac OS. Most platforms can be described as a
combination of the operating system and underlying
hardware. The Java platform differs from most other
platforms in that it's a software-only platform that runs on top
of other hardware-based platforms.
The Java platform has two components:
 The Java Virtual Machine
 The Java Application Programming Interface (API)
You've already been introduced to the Java
Virtual Machine; it's the base for the Java
platform and is ported onto various hardware-
based platforms.
The API is a large collection of ready-made
software components that provide many useful
capabilities. It is grouped into libraries of
related classes and interfaces; these libraries
are known as packages.
The API and Java Virtual Machine insulate the program from the underlying hardware.

As a platform-independent environment, the Java platform can be a bit slower than native
code. However, advances in compiler and virtual machine technologies are bringing
performance close to that of native code without threatening portability.

The terms"Java Virtual Machine" and "JVM" mean a Virtual Machine for the Java platform.
What Java Technology Can Do
The general-purpose, high-level Java programming language is a
powerful software platform. Every full implementation of the
Java platform gives you the following features:
 Development Tools: The development tools provide everything
you'll need for compiling, running, monitoring, debugging, and
documenting your applications. As a new developer, the main
tools you'll be using are the javac compiler, the java
launcher, and the javadoc documentation tool.
. Application Programming Interface (API): The API provides
the core functionality of the Java programming language. It offers
a wide array of useful classes ready for use in your own
applications. It spans everything from basic objects, to
networking and security, to XML generation and database access,
and more.
 Deployment Technologies: The JDK software provides
standard mechanisms such as the Java Web Start software and
Java Plug-In software for deploying your applications to end
users.
 User Interface Toolkits: The JavaFX, Swing, and Java 2D
toolkits make it possible to create sophisticated Graphical
User Interfaces (GUIs).
 Integration Libraries: Integration libraries such as the Java
IDL API, JDBC API, Java Naming and Directory Interface
(JNDI) API, Java RMI, and Java Remote Method Invocation
over Internet Inter-ORB Protocol Technology (Java RMI-IIOP
Technology) enable database access and manipulation of
remote objects.
How Java Technology Can Change Life
You might not be promised fame, fortune, or even a job if you
learn the Java programming language. Still, it is likely to make
your programs better and requires less effort than other
languages. It is believed that Java technology will help you do
the following:
 Get started quickly: Although the Java programming
language is a powerful object-oriented language, it's easy to
learn, especially for programmers already familiar with C or
C++.
 Write less code: Comparisons of program metrics (class
counts, method counts, and so on) suggest that a program
written in the Java programming language can be four times
smaller than the same program written in C++.
 Write better code: The Java programming language encourages
good coding practices, and automatic garbage collection helps
you avoid memory leaks. Its object orientation, its JavaBeans™
component architecture, and its wide-ranging, easily extendible
API let you reuse existing, tested code and introduce fewer bugs.
 Develop programs more quickly: The Java programming
language is simpler than C++, and as such, your development
time could be up to twice as fast when writing in it. Your
programs will also require fewer lines of code.
 Avoid platform dependencies: You can keep your program
portable by avoiding the use of libraries written in other
languages.
 Write once, run anywhere: Because applications written in the
Java programming language are compiled into machine-
independent bytecodes, they run consistently on any Java
platform.
 Distribute software more easily: With
Java Web Start software, users will be able
to launch your applications with a single
click of the mouse. An automatic version
check at startup ensures that users are
always up to date with the latest version of
your software. If an update is available, the
Java Web Start software will automatically
update their installation.
Object-Oriented Programming Concepts
Object
Objects are key to understanding object-oriented technology.
Look around right now and you'll find many examples of
real-world objects: your dog, your desk, your television set,
your bicycle.
Real-world objects share two characteristics: They all have
state and behaviour. Dogs have state (name, colour, breed,
hungry) and behaviour (barking, fetching, wagging tail).
Bicycles also have state (current gear, current pedal cadence,
current speed) and behaviour (changing gear, changing pedal
cadence, applying brakes). Identifying the state and behaviour
for real-world objects is a great way to begin thinking in
terms of object-oriented programming.
Take a minute right now to observe the real-world objects that
are in your immediate area. For each object that you see, ask
yourself two questions: "What possible states can this object be
in?" and "What possible behaviour can this object perform?".
Make sure to write down your observations. As you do, you'll
notice that real-world objects vary in complexity; your desktop
lamp may have only two possible states (on and off) and two
possible behaviours (turn on, turn off), but your desktop radio
might have additional states (on, off, current volume, current
station) and behaviour (turn on, turn off, increase volume,
decrease volume, seek, scan, and tune). You may also notice that
some objects, in turn, will also contain other objects. These real-
world observations all translate into the world of object-oriented
programming.
A software object.
Software objects are conceptually similar to real-world
objects: they too consist of state and related behaviour.
An object stores its state in fields (variables in some
programming languages) and exposes its behaviour
through methods (functions in some programming
languages). Methods operate on an object's internal
state and serve as the primary mechanism for object-to-
object communication. Hiding internal state and
requiring all interaction to be performed through an
object's methods is known as data encapsulation — a
fundamental principle of object-oriented programming.
Consider a bicycle, for example:

A bicycle modeled as a software object.


By attributing state (current speed, current pedal cadence, and
current gear) and providing methods for changing that state, the
object remains in control of how the outside world is allowed to
use it. For example, if the bicycle only has 6 gears, a method to
change gears could reject any value that is less than 1 or greater
than 6.
Bundling code into individual software objects provides a
number of benefits, including:
1.Modularity: The source code for an object can be written and
maintained independently of the source code for other objects.
Once created, an object can be easily passed around inside the
system.
2.Information-hiding: By interacting only with an object's
methods, the details of its internal implementation remain
hidden from the outside world.
3. Code re-use: If an object already exists (perhaps written by
another software developer), you can use that object in your
program. This allows specialists to implement/test/debug
complex, task-specific objects, which you can then trust to run
in your own code.
4. Pluggability and debugging ease: If a particular object turns
out to be problematic, you can simply remove it from your
application and plug in a different object as its replacement.
This is analogous to fixing mechanical problems in the real
world. If a bolt breaks, you replace it, not the entire machine.
Class
In the real world, you'll often find many individual
objects all of the same kind. There may be
thousands of other bicycles in existence, all of the
same make and model. Each bicycle was built
from the same set of blueprints and therefore
contains the same components. In object-oriented
terms, we say that your bicycle is an instance of
the class of objects known as bicycles. A class is
the blueprint from which individual objects are
created.
The following Bicycle class is one possible implementation of a bicycle:

class Bicycle {

int cadence = 0;
int speed = 0;
int gear = 1;

void changeCadence(int newValue) {


cadence = newValue;
}

void changeGear(int newValue) {


gear = newValue;
}

void speedUp(int increment) {


speed = speed + increment;
}

void applyBrakes(int decrement) {


speed = speed - decrement;
}

void printStates() {
System.out.println("cadence:" +
cadence + " speed:" +
speed + " gear:" + gear);
}
}
The syntax of the Java programming language will look new to you,
but the design of this class is based on the previous discussion of
bicycle objects. The fields cadence, speed, and gear represent
the object's state, and the methods (changeCadence,
changeGear, speedUp etc.) define its interaction with the
outside world.
You may have noticed that the Bicycle class does not contain a
main method. That's because it's not a complete application; it's just
the blueprint for bicycles that might be used in an application. The
responsibility of creating and using new Bicycle objects belongs
to some other class in your application.
Here's a BicycleDemo class that creates two separate Bicycle
objects and invokes their methods:
class BicycleDemo {
public static void main(String[] args) {

// Create two different


// Bicycle objects
Bicycle bike1 = new Bicycle();
Bicycle bike2 = new Bicycle();

// Invoke methods on
// those objects
bike1.changeCadence(50);
bike1.speedUp(10);
bike1.changeGear(2);
bike1.printStates();

bike2.changeCadence(50);
bike2.speedUp(10);
bike2.changeGear(2);
bike2.changeCadence(40);
bike2.speedUp(10);
bike2.changeGear(3);
bike2.printStates();
}
}
The output of this test prints the ending
pedal cadence, speed, and gear for the two
bicycles:
cadence:50 speed:10 gear:2
cadence:40 speed:20 gear:3
Inheritance
Different kinds of objects often have a certain amount in common
with each other. Mountain bikes, road bikes, and tandem bikes, for
example, all share the characteristics of bicycles (current speed,
current pedal cadence, current gear). Yet each also defines additional
features that make them different: tandem bicycles have two seats and
two sets of handlebars; road bikes have drop handlebars; some
mountain bikes have an additional chain ring, giving them a lower
gear ratio.
Object-oriented programming allows classes to inherit commonly
used state and behaviour from other classes. In this example,
Bicycle now becomes the superclass of MountainBike,
RoadBike, and TandemBike. In the Java programming language,
each class is allowed to have one direct superclass, and each
superclass has the potential for an unlimited number of subclasses:
A hierarchy of bicycle classes.
The syntax for creating a subclass is simple. At the beginning of your
class declaration, use the extends keyword, followed by the name
of the class to inherit from:
class MountainBike extends Bicycle {

// new fields and methods defining


// a mountain bike would go here

}
This gives MountainBike all the same fields and methods as
Bicycle, yet allows its code to focus exclusively on the features that
make it unique. This makes code for your subclasses easy to read.
However, you must take care to properly document the state and
behaviour that each superclass defines, since that code will not appear
in the source file of each subclass.
Interface
As you've already learned, objects define their interaction
with the outside world through the methods that they
expose. Methods form the object's interface with the
outside world; the buttons on the front of your television
set, for example, are the interface between you and the
electrical wiring on the other side of its plastic casing. You
press the "power" button to turn the television on and off.
In its most common form, an interface is a group of related
methods with empty bodies. A bicycle's behaviour, if
specified as an interface, might appear as follows:
interface Bicycle {

// wheel revolutions per minute


void changeCadence(int newValue);

void changeGear(int newValue);

void speedUp(int increment);

void applyBrakes(int decrement);


}
To implement this interface, the name of your class would
change (to a particular brand of bicycle, for example, such
as ACMEBicycle), and you'd use the implements
keyword in the class declaration:
class ACMEBicycle implements Bicycle {

int cadence = 0;
int speed = 0;
int gear = 1;

// The compiler will now require that methods


// changeCadence, changeGear, speedUp, and applyBrakes
// all be implemented. Compilation will fail if those
// methods are missing from this class.

void changeCadence(int newValue) {


cadence = newValue;
}

void changeGear(int newValue) {


gear = newValue;
}

void speedUp(int increment) {


speed = speed + increment;
}

void applyBrakes(int decrement) {


speed = speed - decrement;
}

void printStates() {
System.out.println("cadence:" +
cadence + " speed:" +
speed + " gear:" + gear);
}
}
Implementing an interface allows a class to become
more formal about the behaviour it promises to
provide. Interfaces form a contract between the class
and the outside world, and this contract is enforced
at build time by the compiler. If your class claims to
implement an interface, all methods defined by that
interface must appear in its source code before the
class will successfully compile.
Note: To actually compile the ACMEBicycle class,
you'll need to add the public keyword to the
beginning of the implemented interface methods.
Package
A package is a namespace that organizes a set of related classes
and interfaces. Conceptually you can think of packages as being
similar to different folders on your computer. You might keep
HTML pages in one folder, images in another, and scripts or
applications in yet another. Because software written in the Java
programming language can be composed of hundreds or
thousands of individual classes, it makes sense to keep things
organized by placing related classes and interfaces into packages.
The Java platform provides an enormous class library (a set of
packages) suitable for use in your own applications. This library
is known as the "Application Programming Interface", or "API"
for short. Its packages represent the tasks most commonly
associated with general-purpose programming.
For example, a String object contains state and behaviour for
character strings; a File object allows a programmer to easily
create, delete, inspect, compare, or modify a file on the
filesystem; a Socket object allows for the creation and use of
network sockets; various GUI objects control buttons and
checkboxes and anything else related to graphical user
interfaces. There are literally thousands of classes to choose
from. This allows you, the programmer, to focus on the design of
your particular application, rather than the infrastructure
required to make it work.
The Java Platform API Specification contains the complete
listing for all packages, interfaces, classes, fields, and methods
supplied by the Java SE platform. Load the page in your browser
and bookmark it. As a programmer, it will become your single
most important piece of reference documentation.
Polymorphism
Polymorphism is a OOPs concept where one name can have
many forms.
For example, you have a smartphone for communication. The
communication mode you choose could be anything. It can be a
call, a text message, a picture message, mail, etc. So, the goal is
common that is communication, but their approach is different.
This is called Polymorphism.

Java Polymorphism in OOP’s with Example


We have one parent class, ‘Account’ with function of deposit
and withdraw. Account has 2 child classes
The operation of deposit and withdraw is same for Saving and
Checking accounts. So the inherited methods from Account
class will work.
Change in Software Requirement
There is a change in the requirement specification, something that is so
common in the software industry. You are supposed to add functionality
privileged Banking Account with Overdraft Facility.
For a background, overdraft is a facility where you can withdraw an amount
more than the available balance in your account.
So, withdraw method for privileged needs is to be implemented afresh. But
you do not change the tested piece of code in Savings and Checking
account. This is advantage of OOPS.
Step 1) Such that when
the "withdrawn" method
for saving account is
called a method from
parent account class is
executed.

Step 2) But when the


"Withdraw" method for
the privileged account
(overdraft facility) is
called withdraw method
defined in the privileged
class is executed. This is
Polymorphism.
Method Overriding
Method Overriding is redefining a super class method in a sub class.

Rules for Method Overriding


•The method signature i.e. method name, parameter list and return
type have to match exactly.
•The overridden method can widen the accessibility but not narrow it,
i.e. if it is private in the base class, the child class can make it public
but not vice versa.
Example
class Doctor{
public void treatPatient(){
// treatPatient method

}
class Surgeon extends Doctor{
public void treatPatient(){
// treatPatient method
}
}
Class run{
public static void main (String args[]){
Doctor doctorObj = new Doctor()
// treatPatient method in class Doctor will be
executed
doctorObj.treatPatient();

Surgeon surgeonObj = new Surgeon();


// treatPatient method in class Surgeon will be
executed
surgeonObj.treatPatient();
}
}
Difference between Overloading and Overriding
Method Overloading Method Overriding
Method overriding is when one of the
Method overloading is in the same class,
methods in the super class is redefined in the
where more than one method have the same
sub-class. In this case, the signature of the
name but different signatures.
method remains the same.
Ex:

class X{
public int sum(){
Ex: // some code
}
}
void sum (int a , int b);
void sum (int a , int b, int c);
class Y extends X{
void sum (float a, double b);
public int sum(){
//overridden method
//signature is same
}
}
What is Dynamic Polymorphism?
Dynamic Polymorphism is the mechanism by which multiple
methods can be defined with same name and signature in the
superclass and subclass. The call to an overridden method are
resolved at run time.

Dynamic Polymorphism Example:


A reference variable of the super class can refer to a sub class
object
Doctor obj = new Surgeon();
Consider the statement
obj.treatPatient();
Here the reference variable "obj" is of the parent class, but the
object it is pointing to is of the child class (as shown in the
diagram).
obj.treatPatient() will execute treatPatient() method of the sub-class -
Surgeon
If a base class reference is used to call a method, the method to be
invoked is decided by the JVM, depending on the object the reference is
pointing to
For example, even though obj is a reference to Doctor, it calls the method
of Surgeon, as it points to a Surgeon object
This is decided during run-time and hence termed dynamic or run-time
polymorphism
Super Keyword
What if the treatPatient method in the Surgeon class wants to execute the
functionality defined in Doctor class and then perform its own specific
functionality?

In this case, keyword super can be used to access methods of the parent
class from the child class.
The treatPatient method in the Surgeon class could be written as:
treatPatient(){
super.treatPatient();
//add code specific to Surgeon
}

The keyword super can be used to access any data member


or methods of the super class in the sub class.
Example:-To learn Inheritance, Polymorphism & super
keyword
Step 1) Copy the following code into an Editor
public class Test{
public static void main(String args[]){
X x= new X();
Y y = new Y();
y.m2();
//x.m1();
//y.m1();
//x = y;// parent pointing to object of
child
//x.m1() ;
//y.a=10;
}

}
class X{
private int a;
int b;
public void m1(){
System.out.println("This is
method m1 of class X");
}
}

class Y extends X{
int c; // new instance variable
of class Y
public void m1(){
// overriden method
System.out.println("This
is method m1 of class Y");
}
public void m2(){
super.m1();
System.out.println("This
is method m2 of class Y");
}
}
Step 2) Save, Compile & Run the code. Observe the output.
Step 3) Uncomments lines # 6-9. Save, Compile & Run the code. Observe
the output.
Step 4) Uncomment line # 10 . Save & Compile the code.
Step 5) Error = ? This is because sub-class cannot access private members of
the super class.
Difference between Static & Dynamic Polymorphism
Static Polymorphism Dynamic Polymorphism
It relates to method overloading. It relates to method overriding.

In case a reference variable is calling an overridden method, the


Errors, if any, are resolved at compile time. Since the code is not
method to be invoked is determined by the object, your reference
executed during compilation, hence the name static.
variable is pointing to. This is can be only determined at runtime
Ex: when code in under execution, hence the name dynamic.
void sum (int a , int b); Ex:
void sum (float a, double b);
//reference of parent pointing to child
int sum (int a, int b); //compiler gives
object
error.
Doctor obj = new Surgeon();
// method of child called
obj.treatPatient();
Abstraction in OOP
Abstraction is selecting data from a larger pool to show only
the relevant details to the object. It helps to reduce
programming complexity and effort. In Java, abstraction is
accomplished using Abstract classes and interfaces. It is one
of the most important concepts of OOPs.

Abstraction concept with an Example


Suppose you want to create a banking application and you are
asked to collect all the information about your customer.
There are chances that you will come up with following
information about the customer
But, not all of the above information is required to create a
banking application.
So, you need to select only the useful information for your
banking application from that pool. Data like name, address,
tax information, etc. make sense for a banking application.
Since we have fetched/removed/selected the customer
information from a larger pool, the process is referred
as Abstraction.
However, the same information once extracted can be used for a wide range of
applications. For instance, you can use the same data for hospital application,
job portal application, a Government database, etc. with little or no
modification. Hence, it becomes your Master Data. This is an advantage of
Abstraction.

How to achieve Abstraction


Abstraction in Java can be achieved using Abstract Class and Abstract Method.
Abstract Class
A class which is declared “abstract” is called as an abstract class. It can have
abstract methods as well as concrete methods. A normal class cannot have
abstract methods.
Abstract Method
A method without a body is known as an Abstract Method. It must be declared
in an abstract class. The abstract method will never be final because the
abstract class must implement all the abstract methods.
Rules of Abstract Method
 Abstract methods do not have an implementation; it
only has method signature
 If a class is using an abstract method they must be
declared abstract. The opposite cannot be true. This
means that an abstract class does not necessarily
have an abstract method.
 If a regular class extends an abstract class, then that
class must implement all the abstract methods of
the abstract parent.
Advantages of Abstraction
 The main benefit of using an abstract class is that it allows
you to group several related classes as siblings.
 Abstraction helps to reduce the complexity of the design and
implementation process of software.

When to use Abstract Methods & Abstract Class


Abstract methods are mostly declared where two or more
subclasses are also doing the same thing in different ways
through different implementations. It also extends the same
Abstract class and offers different implementations of the
abstract methods.
Abstract classes help to describe generic types of behaviours
and object-oriented programming class hierarchy. It also
describes subclasses to offer implementation details of the
abstract
Encapsulation in Java OOPs
Encapsulation is a principle of wrapping data (variables) and code together as a single
unit. It is one of the four OOP concepts. The other three are Inheritance,
Polymorphism, and Abstraction.
To understand what is encapsulation in detail consider the following bank account
class with deposit and show balance methods
class Account {
private int account_number;
private int account_balance;

public void show Data() {


//code to show data
}

public void deposit(int a) {


if (a < 0) {
//show error
} else
account_balance = account_balance + a;
}
}
Suppose a hacker managed to gain access to the code of
your bank account. Now, he tries to deposit amount -100
into your account by two ways. Let see his first method or
approach.
Approach 1: He tries to deposit an invalid amount (say -
100) into your bank account by manipulating the code.
Now, the question is – Is that possible? Let investigate.
Usually, a variable in a class are set as "private" as
shown below. It can only be accessed with the methods
defined in the class. No other class or object can access
them.
If a data member is private, it means it can only be
accessed within the same class. No outside class can
access private data member or variable of other class.
So in our case hacker cannot deposit amount -100 to
your account.
Approach 2: Hacker's first approach failed to
deposit the amount. Next, he tries to do deposit a
amount -100 by using "deposit" method.
But method implementation has a check for
negative values. So the second approach also
fails.

Thus, you never expose your data to an external


party. Which makes your application secure.
The entire code can be thought of as a capsule,
and you can only communicate through the
messages. Hence the name encapsulation.
Data Hiding in Java
Frequently, Java encapsulation is referred as data
hiding. But more than data hiding, encapsulation
concept is meant for better management or
grouping of related data.
To achieve a lesser degree of encapsulation in
Java, you can use modifiers like "protected" or
"public". With encapsulation, developers can
change one part of the code easily without
affecting other.
Advantages of Encapsulation in Java
 Encapsulation is binding the data with its related functionalities.
Here functionalities mean "methods" and data means
"variables"
 So we keep variable and methods in one place. That place is
"class." Class is the base for encapsulation.
 With Java Encapsulation, you can hide (restrict access) to
critical data members in your code, which improves security
 As we discussed earlier, if a data member is declared "private",
then it can only be accessed within the same class. No outside
class can access data member (variable) of other class.
However, if you need to access these variables, you have to use
public "getter" and "setter" methods.
Getter and Setter Methods in Java
If a data member is declared "private", then it can only be accessed within the
same class. No outside class can access data member of that class. If you need to
access these variables, you have to use public "getter" and "setter" methods.
Getter and Setter's methods are used to create, modify, delete and view the
variables values.
The following code is an example of getter and setter methods:
class Account{
private int account_number;
private int account_balance;
// getter method
public int getBalance() {
return this.account_balance;
}
// setter method
public void setNumber(int num) {
this.account_number = num;
}
}
In above example, getBalance() method is getter method that
reads value of variable account_balance and setNumber()
method is setter method that sets or update value for variable
account_number.

Abstraction vs. Encapsulation


Often encapsulation is misunderstood with Abstraction. Lets
study-
 Encapsulation is more about "How" to achieve a functionality
 Abstraction is more about "What" a class can do.
A simple example to understand this difference is a mobile
phone. Where the complex logic in the circuit board is
encapsulated in a touch screen, and the interface is provided to
abstract it out.
Java Variables and Data Types

What is a Variable?
A variable can be thought of as a container which holds value
for you, during the life of a Java program. Every variable is
assigned a data type which designates the type and quantity of
value it can hold.
In order to use a variable in a program you to need to perform
2 steps
1.Variable Declaration
2.Variable Initialization
Variable Declaration:
To declare a variable, you must
specify the data type & give the
variable a unique name.
Examples of other Valid Declarations are
int a,b,c;

float pi;

double d;

char a;
Variable Initialization:
To initialize a variable, you must assign it
a valid value.
Example of other Valid Initializations are
pi =3.14f;
do =20.22d;
a=’v’;
You can combine variable declaration and initialization.

Example :
int a=2,b=4,c=6;

float pi=3.14f;

double do=20.22d;

char a=’v’;
Types of variables
In Java, there are three types of variables:
1. Local Variables
2. Instance Variables
3. Static Variables

1) Local Variables
Local Variables are a variable that are declared inside the body of a method.
2) Instance Variables
Instance variables are defined without the STATIC keyword .They are
defined Outside a method declaration. They are Object specific and are
known as instance variables.
3) Static Variables
Static variables are initialized only once, at the start of the program
execution. These variables should be initialized first, before the initialization
of any instance variables.
Example: Types of Variables in
Java
class Guru99 {
int data = 99;
//instance variable
static int a =
1; //static variable
void method() {
int b = 90;
//local variable
}
}.
Data Types in Java
Data types classify the different values to be stored in
the variable. In java, there are two types of data types:
1.Primitive Data Types
2.Non-primitive Data Types
Primitive Data Types
Primitive Data Types are predefined and available
within the Java language. Primitive values do not
share state with other primitive values.
There are 8 primitive types: byte, short, int, long,
char, float, double, and boolean Integer data types
byte (1 byte)
short (2 bytes)
int (4 bytes)
long (8 bytes)
Floating Data Type
float (4 bytes)

double (8 bytes)
Textual Data Type
char (2 bytes)
Logical
boolean (1 byte) (true/false)
Java Data Types
Data Type Default Value Default size
byte 0 1 byte
short 0 2 bytes
int 0 4 bytes
long 0L 8 bytes
float 0.0f 4 bytes
double 0.0d 8 bytes
boolean false 1 bit
char '\u0000' 2 bytes
Points to Remember:
 All numeric data types are signed(+/-).
 The size of data types remain the same on all
platforms (standardized)
 char data type in Java is 2 bytes because it uses
UNICODE character set. By virtue of it, Java
supports internationalization. UNICODE is a
character set which covers all known scripts and
language in the world

You might also like