CMP 325 Javatech Note
CMP 325 Javatech Note
OBJECT-ORIENTED
PROGRAMMING - JAVA
About the Java Technology
Java technology is both a programming
language and a platform.
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:
class Bicycle {
int cadence = 0;
int speed = 0;
int gear = 1;
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) {
// 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 {
}
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 {
int cadence = 0;
int speed = 0;
int gear = 1;
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.
}
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();
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.
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
}
}
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.
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