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

Unit 1 Java

Uploaded by

Anand Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Unit 1 Java

Uploaded by

Anand Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 74

Object Oriented Thinking:

Everywhere you look in the real world you see objects—people, animals, plants, cars, planes,
buildings, computers and so on. Humans think in terms of objects. Telephones, houses, traffic
lights, microwave ovens and water coolers are just a few more objects. Computer programs, such
as the Java programs you’ll read in this book and the ones you’ll write, are composed of lots of
interacting software objects.

Object-Oriented:
Although influenced by its predecessors, Java was not designed to be source-code compatible
with any other language. This allowed the Java team the freedom to design with a blank slate.
One outcome of this was a clean, usable, pragmatic approach to objects. Borrowing liberally
from many seminal object-software environments of the last few decades, Java manages to strike
a balance between the purist’s “everything is an object” paradigm and the pragmatist’s “stay out
of my way” model. The object model in Java is simple and easy to extend, while simple types,
such as integers, are kept as high-performance nonobjects.
Languages like Java are object oriented. Programming in such a language is called object-
oriented programming (OOP), and it allows computer programmers to implement an object-
oriented design as a working system. Languages like C, on the other hand, are procedural, so
programming tends to be action oriented. In C, the unit of programming is the function.
Groups of actions that perform some common task are formed into functions, and functions are
grouped to form programs. In Java, the unit of programming is the class from which objects are
eventually instantiated (created). Java classes contain methods (which implement operations and
are similar to functions in C) as well as fields (which implement attributes).
Java programmers concentrate on creating classes. Each class contains fields, and the set of
methods that manipulate the fields and provide services to clients (i.e., other classes that use the
class). The programmer uses existing classes as the building blocks for constructing new classes.
-Classes are to objects as blueprints are to houses. Just as we can build many houses from one
blueprint, we can instantiate (create) many objects from one class.
Classes can have relationships with other classes. For example, in an object-oriented design of a
bank, the “bank teller” class needs to relate to the “customer” class, the “cash drawer” class, the
“safe” class, and so on. These relationships are called associations.
NEED FOR OOP PARADIGM:
Object-Oriented Programming:
Object-oriented programming is at the core of Java. In fact, all Java programs are object-oriented
—this isn’t an option the way that it is in C++, for example. OOP is so integral to Java.
Therefore, this chapter begins with a discussion of the theoretical aspects of OOP.
Two Paradigms of Programming:
As you know, all computer programs consist of two elements: code and data. Furthermore,a
program can be conceptually organized around its code or around its data. That is, some
programs are written around “what is happening” and others are written around “who is being
affected.” These are the two paradigms that govern how a program is constructed.

The first way is called the process-oriented model. This approach characterizes a program as a
series of linear steps (that is, code). The process-oriented model can be thought of as code acting
on data. Procedural languages such as C employ this model to considerable success. Problems
with this approach appear as programs grow larger and more complex. To manage increasing
complexity, the second approach, called object-oriented programming, was conceived.
Object-oriented programming organizes a program around its data (that is, objects) and a set of
well-defined interfaces to that data. An object-oriented program can be characterized as data
controlling access to code. As you will see, by switching the controlling entity to data, you can
achieve several organizational benefits.
Procedure oriented Programming:
In this approach, the problem is always considered as a sequence of tasks to be done. A number
of functions are written to accomplish these tasks. Here primary focus on “Functions” and little
attention on data.
There are many high level languages like COBOL, FORTRAN, PASCAL, C used for
conventional programming commonly known as POP.
POP basically consists of writing a list of instructions for the computer to follow, and organizing
these instructions into groups known as functions.
Drawback: It does not model real world problems very well, because functions are action
oriented and do not really corresponding to the elements of the problem.
Chars of POP:
 Emphasis is on doing actions.
 Large programs are divided into smaller programs known as functions.
 Most of the functions shared global data.
 Data move openly around the program from function to function.
 Functions transform data from one form to another.
 Employs top-down approach in program design.

OOP:
OOP allows us to decompose a problem into a number of entities called objects and then builds
data and methods around these entities.
DEF: OOP is an approach that provides a way of modularizing programs by creating portioned
memory area for both data and methods that can used as templates for creating copies of such
modules on demand.
That is ,an object a considered to be a partitioned area of computer memory that stores data and
set of operations that can access that data. Since the memory partitions are independent, the
objects can be used in a variety of different programs without modifications.
OOP Chars:
 Emphasis on data .
 Programs are divided into what are known as methods.
 Data structures are designed such that they characterize the objects.
 Methods that operate on the data of an object are tied together .
 Data is hidden.
 Objects can communicate with each other through methods.
 Reusability.
 Follows bottom-up approach in program design.
Organization of OOP:

A way of viewing World-Agents and Responsibility:


Object-oriented languages use objects to encapsulate the details. Each object simulates an object
in real life, carrying state data as well as behaviors. State data are represented as instance data.
Behaviors are represented as methods.

OOP establish the communication between Distributed Objects. It is possible with the help of
clients and servers in the form of agents. It helps for Distributed Applications.
OOP Chars with Distributed Applications:
Inter process Communication: A distributed application require the participation of two or more
independent entities. To do so, the processes must have the ability to exchange data among
themselves.
Event Synchronization: In a distributed application, the sending and receiving of data among the
participants of a distributed application must be synchronized.
 A distributed system is a collection of independent computers, interconnected via a
network, capable of collaborating on a task.
 Distributed computing is computing performed in a distributed system.
Peer-to-Peer distributed computing: The peer-to-peer paradigm can be implemented with facilities
using any tool that provide message-passing, or with a higher-level tool such as one that supports the
point-to-point model of the Message System paradigm.

For web applications, the web agent is a protocol promoted by the XNSORG (the XNS Public
Trust Organization) for peer-to-peer interprocess communication
“Project JXTA is a set of open, generalized peer-to-peer protocols that allow any connected
device (cell phone, to PDA, PC to server) on the network to communicate and collaborate. JXTA
is short for Juxtapose, as in side by side. It is a recognition that peer to peer is juxtapose to client
server or Web based computing -- what is considered today's traditional computing model. “
The Distributed Objects Paradigms
The idea of applying object orientation to distributed applications is a natural extension
of object-oriented software development.
Applications access objects distributed over a network.
Objects provide methods, through the invocation of which an application obtains access to
services.

Object-oriented paradigms include:


 Remote method invocation (RMI)
 Network services
 Object request broker
 Object spaces
Remote Method Invocation (RMI):
Remote method invocation is the object-oriented equivalent of remote method calls.
In this model, a process invokes the methods in an object, which may reside in a remote
host.
As with RPC, arguments may be passed with the invocation.

The Object Request broker Paradigm:

In the object broker paradigm , an application issues requests to an object request broker
(ORB), which directs the request to an appropriate object that provides the desired
service.
The paradigm closely resembles the remote method invocation model in its support for
remote object access. The difference is that the object request broker in this paradigm
functions as a middleware which allows an application, as an object requestor, to
potentially access multiple remote (or local) objects.

The request broker may also function as an mediator for heterogeneous objects, allowing
interactions among objects implemented using different APIs and /or running on different
platforms.

The Object Space Paradigm:

Perhaps the most abstract of the object-oriented paradigms, the object space paradigm
assumes the existence of logical entities known as object spaces.

The participants of an application converge in a common object space.

A provider places objects as entries into an object space, and requesters who subscribe to
the space access the entries.

In addition to the abstractions provided by other paradigms, the object space paradigm
provides a virtual space or meeting room among provides and requesters of network resources or
objects. This abstraction hides the detail involved in resource or object lookup needed in
paradigms such as remote method invocation, object request broker, or network services.

Current facilities based on this paradigm include JavaSpaces

The Mobile Agent Paradigm

A mobile agent is a transportable program or object.


In this model, an agent is launched from an originating host.

The agent travels from host to host according to an itinerary that it carries.

At each stop, the agent accesses the necessary resources or services, and performs the
necessary tasks to accomplish its mission.

The paradigm offers the abstraction for a transportable program or object.

In lieu of message exchanges, data is carried by the program/object as the program is


transported among the participants.

The Network Services Paradigm:

In this paradigm, service providers register themselves with directory servers on a


network. A process desiring a particular service contacts the directory server at run time,
and, if the service is available, will be provided a reference to the service. Using the
reference, the process interacts with the service.

This paradigm is essentially an extension of the remote method call paradigm. The
difference is that service objects are registered with a global directory service, allowing
them to be look up and accessed by service requestors on a federated network.
Java’s Jini technology is based on this paradigm

The Collaborative Application (Groupware) Paradigm:

The Collaborative Application (Groupware) Paradigm:

In this model, processes participate in a collaborative session as a group. Each


participating process may contribute input to part or all of the group.

Processes may do so using:

 multicasting to send data to all or part of the group, or they may use a

 virtual sketchpads or whiteboards which allows each participant to read and write
data to a shared display.

The Architecture of Distributed Applications:


MESSAGES:

An OOP consists of objects that communicate with each other. The process of programming in
an object-Oriented language, therefore, involves the basic concepts:

1. Creating classes that define objects and their behavior.


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.

The concept of message passing makes it easier to talk about building systems that directy model
or simulate their real-world counter parts.
A message for an object is a request for execution of a procedure, and therefore will invoke a
procedure in the receiving object that generates the desired results.
The Message Passing Paradigm:

Message passing is the most fundamental paradigm for distributed applications.

A process sends a message representing a request.

The message is delivered to a receiver, which processes the request, and sends a message
in response.
In turn, the reply may trigger a further request, which leads to a subsequent reply, and so forth.

Proce ss A
Proce ss B

a m essage

Me ssage passin g

The basic operations required to support the basic message passing paradigm are send,
and receive.
For connection-oriented communication, the operations connect and disconnect are also
required.
With the abstraction provided by this model, the interconnected processes perform input
and output to each other, in a manner similar to file I/O. The I/O operations encapsulate
the detail of network communication at the operating-system level.
The socket application programming interface is based on this paradigm.
The Client-Server Paradigm:

Perhaps the best known paradigm for network applications, the client-server model assigns
asymmetric roles to two collaborating processes.

One process, the server, plays the role of a service provider which waits passively for the arrival
of requests. The other, the client, issues specific requests to the server and awaits its response.

Simple in concept, the client-server model provides an efficient abstraction for the
delivery of network services.
Operations required include those for a server process to listen and to accept requests,
and for a client process to issue requests and accept responses.
By assigning asymmetric roles to the two sides, event synchronization is simplified: the
server process waits for requests, and the client in turn waits for responses.
Many Internet services are client-server applications. These services are often known by the
protocol that the application implements. Well known Internet services include HTTP, FTP,
DNS, finger, gopher, etc.

The Message System Paradigm:

The Message System or Message-Oriented Middleware (MOM) paradigm is an


elaboration of the basic message-passing paradigm.
In this paradigm, a message system serves as an intermediary among separate,
independent processes.
The message system acts as a switch for messages, through which processes exchange
messages asynchronously, in a decoupled manner.
A sender deposits a message with the message system, which forwards it to a message
queue associated with each receiver. Once a message is sent, the sender is free to move
on to other tasks.
re ce iv e rs
m e ssage s yste m s e n de r
...

...

Two subtypes of message system models:

The Point-To-Point Message Model:

In this model, a message system forwards a message from the sender to the receiver’s
message queue. Unlike the basic message passing model, the middleware provides a
message depository, and allows the sending and the receiving to be decoupled. Via the
middleware, a sender deposits a message in the message queue of the receiving process.
A receiving process extracts the messages from its message queue, and handles each one
accordingly.
Compared to the basic message-passing model, this paradigm provides the additional
abstraction for asynchronous operations. To achieve the same effect with basic message-
passing, a developer will have to make use of threads or child processes.
The Publish/Subscribe Message Model:
In this model, each message is associated with a specific topic or event. Applications
interested in he occurrence of a specific event may subscribe to messages for that event.
When the awaited event occurs, the process publishes a message announcing the event or
topic. The middleware message system distributes the message to all its subscribers.
The publish/subscribe message model offers a powerful abstraction for multicasting or
group communication. The publish operation allows a process to multicast to a group of
processes, and the subscribe operation allows a process to listen for such multicast.
Remote Procedure Call:
As applications grew increasingly complex, it became desirable to have a paradigm
which allows distributed software to be programmed in a manner similar to conventional
applications which run on a single processor.
The Remote Procedure Call (RPC) model provides such an abstraction. Using this model,
interprocess communications proceed as procedure, or function, calls, which are familiar
to application programmers.
A remote procedure call involves two independent processes, which may reside on
separate machines. A process, A, wishing to make a request to another process, B, issues
a procedure call to B, passing with the call a list of argument values. As in the case of
local procedure calls, a remote procedure call triggers a predefined action in a procedure
provided by process B. At the completion of the procedure, process B returns a value to
process A.
RPC allows programmers to build network applications using a programming construct
similar to the local procedure call, providing a convenient abstraction for both
interprocess communication and event synchronization.
Since its introduction in the early 1980s, the Remote Procedure Call model has been
widely in use in network applications.
There are two prevalent APIs for Remote Procedure Calls.
 The Open Network Computing Remote Procedure Call, evolved from the RPC
API originated from Sun Microsystems in the early 1980s.
 The Open Group Distributed Computing Environment (DCE) RPC.
Both APIs provide a tool, rpcgen, for transforming remote procedure calls to local
procedure calls to the stub.

MESSAGE: SOFTWARE OBJECTS INTERACT AND COMMUNICATE WITH EACH OTHER USING
MESSAGES.

History of Java:
Before Proceeding with java, first we need to know what is a programming language?

A Programming language is an artificial language designed communicate


instructions to a machine, particularly a computer. Programming languages can be used to
create programs that control the behavior of a machine. In history there were many programming
languages, in 1970, the most popular programming language was C. Since C was the most
powerful language many people were using this language. This language was being used in
business applications, scientific applications, artificial applications etc. Since, C has the
procedure oriented programming features, it was having many limitations

Limitations of C are:

 Difficult to implement today's client requirements.


 No code reusability.
 No Code Enhancement
 Platform Dependent
 As length of the application increases, causes slow in performance.
 Code maintenance and enhancements are difficult.
 No Exception Handling mechanisms

In order to solve those disadvantages and new programming paradigm was introduce, named
Object Oriented Programming(OOPs).

OOPs is basically based on objects and classes. OOPs can be defined as grouping of data and
methods. OOPs basically have 4 features.

1. Inheritance
2. Polymorphism
3. Abstraction
4. Encapsulation

During the late 1970s and early 1980s, C became the dominant computer programming
language, but in C complexity was more. The increasing complexity of programs has driven the
need for better ways to manage that complexity. C++ is a response to that need. C++ was
developed from C syntax, all the syntaxes were similar in C++ with C the only change was C++
was having OOPs features. By the end of the 1980s and the early 1990s, object-oriented
programming using C++ took hold. C++ has overcome all the disadvantages of C, but still C++
was having its own disadvantages.

 Pointers.
 Explicitly memory allocation and deallocation.
 Platform Dependent.
Creation Of java:

Java was created by James Gosling, Patrick Naughton, Chris Warth, Ed Frank, and Mike
Sheridan at Sun Microsystems, Inc. in 1991. It took 18 months to develop the first working
version. This language was initially called “Oak” but was renamed “Java” in 1995. Java’s
primary motivation was the need for a platform-independent language that could be used to
create software to be embedded in various consumer electronic devices, such as microwave
ovens and remote controls. The trouble with C and C++ (and most other languages) is that they
are designed to be compiled for a specific target. Although it is possible to compile a C++
program for just about any type of CPU, to do so requires a full C++ compiler targeted for that
CPU. The problem is that compilers are expensive and time-consuming to create. An easier—
and more cost-efficient—solution was needed. In an attempt to find such a solution, Gosling and
others began work on a portable, platform-independent language that could be used to produce
code that would run on a variety of CPUs under differing environments. This effort ultimately
led to the creation of Java.

The Java Buzzwords

• Simple
• Secure
• Portable
• Object-oriented
• Robust
• Multithreaded
• Architecture-neutral
• Interpreted
• High performance
• Distributed
• Dynamic
Platform independent:
Java is platform independent because java programs are executed by the any operating
system irrespective of its development and compilation.
Simple:
There are various features that makes the java as a simple language. Programs are easy to write
and debug because java does not use the pointers explicitly. The other reason is, if we know C and C++
then it is very easy to learn java, as we know all the syntaxes and rules of java are taken from C and C++.
It also has the automatic memory allocation and deallocation system.

Secure:

Java provides internal and external security. Internal security is provided by the
JVM(Java Virtual Macchine). External security is provided by the developer using cryptographic
techniques(Encryption,Decryption).

Portable:
The feature Write-once-run-anywhere makes the java language portable. Byte code
and JVM in java makes java as a platform independent.

Object-oriented:
Java is pure Object oriented programming language because everything we write in java
comes under classes and objects. Java is pure object oriented programming language but it is not
100% object oriented programming language because java uses primitive data types which are
defined using C and C++.
Robust:
Java has the strong memory allocation and automatic garbage collection mechanism. It
provides the powerful exception handling and type checking mechanism as compare to other
programming languages. Compiler checks the program whether there any error and interpreter
checks any run time error and makes the system secure from crash. All of the above features
make the java language robust.
Multithreaded:
Java supports multithreaded programming, which allows you to write programs that do
many things simultaneously. Thread is nothing but a piece of program and multithreading means
executing more than one program simultaneously. For example consider an online examination
application, in this application at one side one timer will be running and at the same time
application will be displaying you question with options.
Architecture-neutral:
One of the main problems facing programmers is that no guarantee exists that if you write a
program today, it will run tomorrow—even on the same machine. Operating system upgrades,
processor upgrades, and changes in core system resources can all combine to make a program
malfunction. But in java this problem was overcome. We can run java program anytime, anywhere,
forever even though operating system, processor or other system resources upgrades.

Interpreted& High performance:


Java enables the creation of cross-platform programs by compiling into an intermediate
representation called Java bytecode. This code can be executed on any system that implements
the Java Virtual Machine. the Java bytecode was carefully designed so that it would be easy to
translate directly into native machine code for very high performance by using a just-in-time
compiler.
Distributed:
Java is designed for the distributed environment of the Internet, because it handles TCP/IP
and HTTP protocols. Java achieves distributed features by RMI and by Socket Programming.

Dynamic:
Java programs carry with them substantial amounts of run-time type information that is
used to verify and resolve accesses to objects at run time. This makes it possible to dynamically
link code in a safe and expedient manner.
A First Simple Program:

Now that the basic object-oriented underpinning of Java has been discussed, let’s look at some
actual Java programs. Let’s start by compiling and running the short sample program shown
here.

public class Example


{
public static void main(String args[])
{
System.out.println("This is a simple Java program.");
}
}

Write the above program in any text editor or in note pad and save it as Example.java. If we are
declaring our class as a public then we need to give the file name as the class name. If we are not
declaring the class as a public then we can give any name to the file with the extension .java.

Note: before showing compilation show how to set the “path”.

For Compilation use the command

Syntax: javac Filename.java

ex: javac Example.java

For Execution use the command

Syntax: Java Classname

Ex: java Example

Note: For execution we will use the class name not the filename. In a file if we have more than one class
then we will use the class which has main method.

A Closer Look at the First Program:

class Example
This line uses the keyword class to declare that a new class is being defined. Example is an
identifier that is the name of the class. The entire class definition, including all of its members,
will be between the opening curly brace ({) and the closing curly brace (}).
public static void main(String args[])
This line begins the main( ) method. This is the line at which every java program will begin
executing. All Java applications begin execution by calling main( ). (This is just like C/C++.)
The public keyword is an access specifier, which allows the programmer to control the visibility
of class members. When a class member is preceded by public, then that member may be
accessed by code outside the class in which it is declared. (The opposite of public is private,
which prevents a member from being used by code defined outside of its class.) In this case,
main( ) must be declared as public, since it must be called by code outside of its class when the
program is started. The keyword static allows main( ) to be called without having to instantiate a
particular instance of the class. This is necessary since main( ) is called by the Java interpreter
before any objects are made. The keyword void simply tells the compiler that main( ) does not
return a value.
As main() is a method it takes a array argument of type String. Whenever we are providing
inputs to the program through command line, then those inputs are stored in args[] which is of
type String. Whatever input we provide they are taken as String only, later in the program we can
convert.
All methods in java starts with opening curly brace({) and ends with closing curly brace(}).
System.out.println("This is a simple Java program.");
This line outputs the string “This is a simple Java program.” followed by a new line on the
screen. Output is actually accomplished by the built-in println( ) method which is defined in
PrintStream class. System is a predefined class available in java.lang package. In System class
PrintStream object is created with the name out, and this object is a static.
Data types:
Data types are used to allocate sufficient memory to the variables. Data types
represent the different values to be stored in the variable. In java, there are two types of data
types:
o Primitive data types
o Non-primitive data types
Java defines eight simple (or elemental) types of data: byte, short, int, long, char, float, double,
and boolean.

These can be put in four groups:


 Integers: This group includes byte, short, int, and long, which are for whole valued
signed numbers.
 Floating point numbers: This group includes float and double, which represent
numbers with fractional precision.
 Characters: This group includes char, which represents symbols in a character set, like
letters and numbers.
 Boolean: This group includes boolean, which is a special type for representing true/false
values.

Datatype Memory Range


Byte 1 byte(8 bits) -27 to 27-1
Short 2 bytes(16 bits) -215 to 215-1
Int 4 bytes(32 bits) -231 to 231-1
Long 8 bytes(64 bits) -263 to 263-1
Float 4 bytes(32 bits) -231 to 231-1
Double 8 bytes(64 bits) -263 to 263-1
Char 2 bytes(16 bits) -215 to 215-1
boolean 1 bit ---------------------------
Primitive data types are capable of holding only one value in a variable at a time.

Non primitive data types are capable of holding more than one value at a time.

Variables:
The variable is the basic unit of storage in a Java program. A variable is defined by the
combination of an identifier, a type, and an optional initializer. In addition, all variables have a
scope, which defines their visibility, and a lifetime. These elements are examined next.

Declaring a Variable

In Java, all variables must be declared before they can be used. The basic form of a variable

declaration is shown here:

type identifier [ = value][, identifier [= value] ...] ;


The identifier is the name of the variable. You can initialize the variable by specifying an equal
sign and a value. Keep in mind that the initialization expression must result in a value of the
same (or compatible) type as that specified for the variable. To declare more than one variable of
the specified type, use a comma-separated list.
int a, b, c; // declares three ints, a, b, and c.
int d = 3, e, f = 5; // declares three more ints, initializing
// d and f.
byte z = 22; // initializes z.
double pi = 3.14159; // declares an approximation of pi.
char x = 'x'; // the variable x has the value 'x'.
The identifiers that you choose have nothing intrinsic in their names that indicates their type.
Java allows any properly formed identifier to have any declared type.
Dynamic Initialization
Although the preceding examples have used only constants as initializers, Java allows variables
to be initialized dynamically, using any expression valid at the time the variable is declared.
For example, here is a short program that computes the length of the hypotenuse of a right
triangle given the lengths of its two opposing sides:
// Demonstrate dynamic initialization.
class DynInit {
public static void main(String args[]) {
double a = 3.0, b = 4.0;
// c is dynamically initialized
double c = Math.sqrt(a * a + b * b);
System.out.println("Hypotenuse is " + c);
}
}
Here, three local variables—a, b, and c—are declared. The first two, a and b, are initialized by
constants. However, c is initialized dynamically to the length of the hypotenuse (using the
Pythagorean theorem). The program uses another of Java’s built-in methods, sqrt( ), which is a
member of theMath class, to compute the square root of its argument. The key point here is that
the initialization expression may use any element valid at the time of the initialization, including
calls to methods, other variables, or literals.

The Scope and Lifetime of Variables:

Programming languages define two general categories of scopes: global and local.
Java allows variables to be declared within any block. A block is begun with an opening curly
brace and ended by a closing curly brace. A block defines a scope. Thus, each time you start a
new block, you are creating a new scope. Whenever we are creating a variable within a block,
the scope of the variable will be within the block, or in inner blocks.
Note: Scope of a variable means the area in which variable can be used.
Eg:
{ // block 1
int a , b ;
{ // block 2
int c ;
-------;
-------;
}
-------;
-------;
}
In the above example variable a and b can be used in block1 and as well as in block 2. Variable c
can only be used in block 2 but not in block 1.
Local Variable
A variable declared inside the body of the method is called local variable. You can use this
variable only within that method and the other methods in the class aren't even aware that the
variable exists.
A local variable cannot be defined with "static" keyword.
Instance Variable
A variable declared inside the class but outside the body of the method, is called instance
variable.
It is called instance variable because its value is instance specific and is not shared among
instances.
Static variable
A variable which is declared as static is called static variable. It cannot be local. You can create a
single copy of static variable and share among all the instances of the class. Memory allocation
for static variable happens only once when the class is loaded in the memory.
class Student
{
String name="";//instance variable
int age=0;//instance variable
static String college="KITS for Women KODAD";//static variable
void details()
{
int pincode=508206;//local variable
System.out.println("Hello "+name);
System.out.println("Your age is"+age);
System.out.println("Your college name is"+college);
System.out.println("pincode is="+pincode);
}
public static void main(String[] args)
{
Student stu501=new Student();
stu501.name="Anand Kumar";
stu501.age=25;
//stu501.pincode=508207; this is local variable cant be accessed out side of the
method
stu501.details();
Student stu502=new Student();
stu502.name="Suresh kumar";
stu502.age=35;
//stu502.pincode=508207; this is local variable cant be accssed out side of the
method
stu502.details();
}
}
Output:
C:\Users\sriram\Desktop>javac Student.java

C:\Users\sriram\Desktop>java Student

Hello Anand Kumar

Your age is25

Your college name isKITS for Women KODAD

pincode is=508206

Hello Suresh kumar

Your age is35

Your college name isKITS for Women KODAD

pincode is=508206

Classes and Objects:


Classes are used to bind the data and code into a single container. Class contain data members
and methods.

A simplified general form of a class definition is shown here:

class classname {

type instance-variable1;
type instance-variable2;
// ...
type instance-variableN;

type methodname1(parameter-list) {
// body of method
}
type methodname2(parameter-list) {
// body of method
}
// ...
type methodnameN(parameter-list) {
// body of method
}
}

The data, or variables, defined within a class are called instance variables. The code is contained
within methods. Collectively, the methods and variables defined within a class are called
members of the class. In most classes, the instance variables are acted upon and accessed by the
methods defined for that class. Thus, as a general rule, it is the methods that determine how a
class’ data can be used.
Variables defined within a class are called instance variables because each instance of the class
(that is, each object of the class) contains its own copy of these variables. Thus, the data for one
object is separate and unique from the data for another. We will come back to this point shortly,
but it is an important concept to learn early.
All methods have the same general form as main( ), which we have been using thus far.
However, most methods will not be specified as static or public. Notice that the general form
of a class does not specify a main( ) method. Java classes do not need to have a main( ) method.

Objects:
Object is nothing but instance of a variable / blue print of a class. Objects have states and
behaviors. Example: A dog has states - color, name, breed as well as behaviors – wagging the
tail, barking, eating.

There are three steps when creating an object from a class −

 Declaration − A variable declaration with a variable name with an object type.


 Instantiation − The 'new' keyword is used to create the object.
 Initialization − The 'new' keyword is followed by a call to a constructor. This call
initializes the new object.

Syntax:

class ClassName

-------------------

-------------------

public static void main(String[] args)

ClassName objectName1=new ClassName(); /*This is one way*/

ClassName objectName2;

objectName2=new ClassName(); /*this is anotherway*/

Example:
public class Puppy {

public show(String name) {

// This constructor has one parameter, name.

System.out.println("Passed Name is :" + name );

public static void main(String []args) {

// Following statement would create an object myPuppy

Puppy myPuppy = new Puppy();

myPuppy.show(“Blacky”);/*method calling*/

Example:
Smartphone

(class)

Oppo
Lenovo Samsung
(object)
(object) (object)

class Smartphone
{

String modelno="";

String ram="";

String internal="";

void details()

System.out.println("model no is ="+modelno);

System.out.println("ram is="+ram);

System.out.println("internal memory is="+internal);

public static void main(String[] args)

Smartphone lenovo=new Smartphone();

lenovo.modelno="k3note";

lenovo.ram="2 gb";

lenovo.internal="16 gb";

lenovo.details();

Smartphone oppo=new Smartphone();

oppo.modelno="F3 plus";

oppo.ram="3 gb";

oppo.internal="32 gb";

oppo.details();

Expressions:
An expression is a construct made up of variables, operators, and method invocations,
which are constructed according to the syntax of the language, that evaluates to a single value.
You've already seen examples of expressions, illustrated in bold below:

int cadence = 0;
anArray[0] = 100;
System.out.println("Element 1 at index 0: " + anArray[0]);

int result = 1 + 2; // result is now 3


if (value1 == value2)
System.out.println("value1 == value2");

The data type of the value returned by an expression depends on the elements used in the
expression. The expression cadence = 0 returns an int because the assignment operator returns
a value of the same data type as its left-hand operand; in this case, cadence is an int. As you
can see from the other expressions, an expression can return other types of values as well, such
as boolean or String.

Methods:
A Java method is a block of code(collection of statements )that are grouped together to
perform an operation. Methods are having the following syntaxes:

Syntax1:
returntype methodname(Parameterlist)
{
Method body/ statements
}
Ex:
void show()
{
System.out.println(“This is show() method”);
}
Methods may have an optional return statement.
Syntax2:
returntype methodname(Parameterlist)
{
Method body/statements
return value;
}
Ex:
int addition(int num1,int num2)
{
int result=num1+num2;
return result;
}

Constructor:
Constructor is similar to a method and the name of the constructor should be equal to the
class.
1)Constructors are used to eliminating the default values of the variables.
2)Constructors are used to initializing the objects.
Syntax:-

Classname (parameter-list)

------------ statements
------------

Method Constructor
1) Method name can be any user defined 1) It’s name should be the class name
name 2) It will be called automatically whenever
2) It should be called explicitly
object is created
3) Method should have return type (any data 3) Constructor should not have any return
type (or) void)
type (even void also)
4) Method can be either static/final/abstract 4) Constructor cannot be static/final/abstract

Types of constructor:-

These are classified into following types

Constructor

Deafult constructor parameterized Constructor

Default Constructor: If any constructor doesn’t have list of parameters in its signature known
as non parameterized or default constructor

Syntax:-

Classname()

Example:

class Kits

String name=””;

Kits()

name=”Kits for women kodad”;

System.out.println(name);

}
public static void main(String[] args)

Kits k=new Kits();/*by this constructor called automatically*/

Parameterized constructor:-

It is any constructor contains list of parameters in it’s signature know as parameterized


constructor.

Syntax:-

Classname (datatype var1, datatype var2)

---------------------------------------

---------------------------------------

Example:
class Example
{
Example(String name)
{
System.out.println(name);
}
public static void main(String args[])
{
Example ex=new Example(“Anand Kumar”);/* Calling of constructor by passing
argument*/
}
}
Arrays in Java:
Normally, array is a collection of similar type of elements that have contiguous
memory location.

Java array is an object the contains elements of similar data type. It is a data structure
where we store similar elements. We can store only fixed set of elements in a java array.

How to declare an array:


datatype[] arrName;
arrName=new datatype[Size Of Array];
(or)
datatype arrName[]=new datatype[Size of Array];
Example:
int[] rollno;
rollno=new int[10];
(or)
int rollno[]=new int[10];
Consider the following example:
class Testarray{
public static void main(String args[]){

int a[]=new int[5];//declaration and instantiation


a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//printing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}
}

Multidimensional array:

In such case, data is stored in row and column based index (also known as matrix form).

dataType [ ][ ] arrayRefVar;
(or)
dataType arrayRefVar[ ][ ];

Example to instantiate Multidimensional Array in java


int[ ][ ] arr=new int[3][3]; //3 row and 3 column

Example to initialize Multidimensional Array in java


arr[0][0]=1;
arr[0][1]=2;
arr[0][2]=3;
arr[1][0]=4;
arr[1][1]=5;
arr[1][2]=6;
arr[2][0]=7;
arr[2][1]=8;
arr[2][2]=9;

Program:
class Testarray3{

public static void main(String args[]){

//declaring and initializing 2D array

int arr[][]={{1,2,3},{2,4,5},{4,4,5}};

//printing 2D array

for(int i=0;i<3;i++){

for(int j=0;j<3;j++){

System.out.print(arr[i][j]+" ");

System.out.println();

Control Statements:

Java has two control statements: if and switch. These statements allow you to control the
flow of your program’s execution based upon conditions known only during run time.
If statement

The if statement
is Java’s conditional branch statement. It can be used to route program execution through two
different paths. Here is the general form of the if statement:
if (condition)
{
statement1; /* if condition is true it is executed*/
}
else
{
statement2; /* if condition is false it is executed*/
}
In above syntax if condition is true if block is executed, otherwise by neglecting if block else
block will be executed.

Example:

class IfEx
{
void check(int age)
{
if (age>17)
{
System.out.println("You are eligible for vote");
}
else
{
System.out.println("You are not eligible for vote");
}
}
public static void main(String[] args)
{
IfEx i=new IfEx();
i.check(10);
i.check(20);
}
}
The if-else-if Ladder
A common programming construct that is based upon a sequence of nested ifs is the
if-else-if ladder. It looks like this:
if(condition)
statement;
else if(condition)
statement;
else if(condition)
statement;
...
else
statement;

class Grade
{
char grade;
void check(int per)
{
if(per>90&&per<100)
{
grade='A';
}
else if(per>75&&per<90)
{
grade='B';
}
else if(per>60&&per<75)
{
grade='C';
}
else if(per>40&&per<60)
{
grade='D';
}
else
{
System.out.println("Fail");
}
System.out.println("your grade is "+grade);
}
public static void main(String[] args)
{
Grade og=new Grade();
og.check(50);
og.check(91);
}
}
Switch Statement:

The switch statement is Java’s multiway branch statement. It provides an easy way to
dispatch execution to different parts of your code based on the value of an expression. As such, it
often provides a better alternative than a large series of if-else-if statements. Here is the general
form of a switch statement:

switch (expression) {
case value1:
// statement sequencebreak;
case value2:
// statement sequence
break;
...
case valueN:
// statement sequence
break;
default:
// default statement sequence
}

The expression must be of type byte, short, int, or char; each of the values specified in the case
statements must be of a type compatible with the expression. An enumeration value can also be
used to control a switch statement.
// A simple example of the switch.
class SampleSwitch
class Month
{
void select(int num)
{
switch (num)
{
case 1:
System.out.println("you selected january");
break;
case 2:
System.out.println("you selected february");
break;
case 3:
System.out.println("you selected March");
break;
case 4:
System.out.println("you selected April");
break;
case 5:
System.out.println("you selected May");
break;
case 6:
System.out.println("you selected june");
break;
default:
System.out.println("you selected wrong num");
break;
}
}
public static void main(String[] args)
{
Month om=new Month();
om.select(6);
om.select(10);
}
}
break:
The break statement is used inside the switch to terminate a statement sequence. When
a break statement is encountered, execution branches to the first line of code that follows the
entire switch statement. This has the effect of “jumping out” of the switch.
class BreakEx
{
public static void main(String[] args)
{
int a[]={1,2,3,4,5,6,7,8,9,10};
for (int i=0;i<10 ;i++ )
{
System.out.println(a[i]);
if(a[i]==5)
{
break;
}
}
}
}
Continue:
The Java continue statement is used to continue loop. It continues the current flow of the
program and skips the remaining code at specified condition. In case of inner loop, it continues
only inner loop.
class Continue
{
public static void main(String[] args)
{
int a[]={1,2,3,4,5,6,7,8,9,10};
for (int i=0;i<10 ;i++ )
{
if(a[i]%2==0)
{
continue;
}
System.out.println(a[i]);

}
}
}

Loops:

Loops are used whenever you want to perform same operation for multiple times.

while Loop:

The while loop is Java’s most fundamental loop statement. It repeats a statement or block while
its controlling expression is true. Here is its general form:
while(condition) {
// body of loop
}
The condition can be any Boolean expression. The body of the loop will be executed as long as
the conditional expression is true. When condition becomes false, control passes to the next line
of code immediately following the loop. The curly braces are unnecessary if only a single
statement is being repeated.
Example:
// Demonstrate the while loop.
class HelloWhile
{
public static void main(String[] args)
{
int i=0;
while (i<10)
{
System.out.println("Hello");
i++;
}

}
}
Since the while loop evaluates its conditional expression at the top of the loop, the body of the
loop will not execute even once if the condition is false to begin with. For example, in the
following fragment, the call to println( ) is never executed:
do-while:
The do-while loop always executes its body at least once, because its conditional
expression is at the bottom of the loop. Its general form is:
do {
// body of loop
} while (condition);
Each iteration of the do-while loop first executes the body of the loop and then evaluates
the conditional expression. If this expression is true, the loop will repeat. Otherwise, the loop
terminates. As with all of Java’s loops, condition must be a Boolean expression.
Here is a reworked version of the “tick” program that demonstrates the do-while loop.
It generates the same output as before.
// Demonstrate the do-while loop.
class HelloWhile
{
public static void main(String[] args)
{
int i=0;
do
{
System.out.println("Hello");
i++;
}
while (i<10);
}
}
for loop:
This loop is used whenever we know the number of iterations.
Here is the general form of the traditional for statement:
for(initialization; condition; iteration) {
// body
}
The for loop operates as follows. When the loop first starts, the initialization portion of the loop
is executed. Generally, this is an expression that sets the value of the loop control variable,
which acts as a counter that controls the loop. It is important to understand that the initialization
expression is only executed once. Next, condition is evaluated. This must be a Boolean
expression. It usually tests the loop control variable against a target value. If this expression is
true, then the body of the loop is executed. If it is false, the loop terminates. Next, the iteration
portion of the loop is executed. This is usually an expression that increments or decrements the
loop control variable. The loop then iterates, first evaluating the conditional expression, then
executing the body of the loop, and then executing the iteration expression with each pass. This
process repeats until the controlling expression is false. Here is a version of the “tick” program
that uses a for loop:
// Demonstrate the for loop.
class HelloFor
{
public static void main(String[] args)
{
for (int i=0;i<10 ;i++ )
{
System.out.println("Hello");
}
}
}
Operators:
Operators are special symbols that perform specific operations on one, two, or
three operands, and then return a result. Most of its operators can be divided into the following
four groups: arithmetic, bitwise, relational, and logical. Java also defines some additional
operators that handle certain special situations.
Arithmetic Operators
Arithmetic operators are used in mathematical expressions in the same way that they are used in
algebra. The following table lists the arithmetic operators:

The operands of the arithmetic operators must be of a numeric type. You cannot use them on
boolean types, but you can use them on char types, since the char type in Java is, essentially, a
subset of int.
The Bitwise Operators
Java defines several bitwise operators that can be applied to the integer types, long, int, short,
char, and byte. These operators act upon the individual bits of their operands. They are
summarized in the following table:
Relational Operators
The relational operators determine the relationship that one operand has to the other.
Specifically, they determine equality and ordering. The relational operators are shown here:

Boolean Logical Operators

The Boolean logical operators shown here operate only on boolean operands. All of the binary
logical operators combine two boolean values to form a resultant boolean value.
The logical Boolean operators, &, |, and ^, operate on boolean values in the same way that they
operate on the bits of an integer. The logical ! operator inverts the Boolean state:
!true == false and !false == true. The following table shows the effect of each logical operation:
Inheritance: Acquiring the properties of one class another one or classes is called inheritance.
(or)

It is a process of deriving new class from already existing class. Here already existing class is
called parent class/base class/super class. Newly derived class is called sub/child class.

Extending the properties from one class from another class is known as inheritance

 The main advantage with inheritance is code reusability.


 That means all the properties of a class can be reused many number of times in a class
without redeclaration .
 In java by inheriting one class into another class we can reuse the properties, inheritance
can be achieved using extends keyword.

Most people naturally view the world as made up of ojects that are related to each other in a
hierarchical way.

Inheritance: A new class (subclass, child class) is derived from the existing class(base class,
parent class).

Syntax:

class A

Class B extends A

Super class: In Java a class that is inherited from is called a super class.
Sub class: The class that does the inheriting is called as subclass.

Therefore, a subclass is a specialized version of a super class. It inherits all of the instance
variables and methods defined by the super class and add its own, unique elements.
Extends: To inherit a class, you simply incorporate the definition of one class into another by
using the extends keyword.
The “extends” keyword indicates that the properties of the super class name are extended to the
subclass name. The sub class now contain its own variables and methods as well those of the
super class. This kind of situation occurs when we want to add some more properties to an
existing class without actually modifying the super class members.
To see how, let’s begin with a short example. The following program creates a super class called
A and a subclass called B. Notice how the keyword extends is used to create a subclass of A.
Inheritance Hierarchies:
In any object oriented programming language inheritance should be done from top to
bottom. That means base class properties inherited into child class but not derived class
properties into base class.

Types of inheritance :

It is many classified into 5 types

1.simple/single inheritance

2.multilevel

3.hierarchial

4. multiple

5.hybrid

Single Inheritance: Simple Inheritance is also called as single Inheritance. Here One subclass is
deriving from one super class.
A SUPER CLASS A
EXTENDS
SUB CLASS B
B
Example for single inheritance:
import java.util.Scanner;
class Read
{
int a,b,c;
Scanner sc=new Scanner(System.in);
void read()
{
a=sc.nextInt();
b=sc.nextInt();
}
}
class Addition extends Read
{
void add()
{
read();
c=a+b;
System.out.println("Addition is "+c);
}
public static void main(String[] args)
{
Addition oa=new Addition();
oa.add();
}
}
Multiple Inheritance: Deriving one subclass from more than one super classes is called
multiple inheritance.

We know that in multiple inheritance, sub class is derived from multiple super classes. If two
super classes have sane names for their members then which member is inherited into the sub
class is the main confusion in multiple inheritance. This is the reason, Java does not support the
concept of multiple inheritance,. This confusion is reduced by using multiple interfaces to
achieve multiple inheritance.
Hierarchical Inheritance: Multiple classes derived from single classi.e; there exist single super
class multiple sub classes.

import java.util.Scanner;
class Read
{
int a,b,c;
Scanner sc=new Scanner(System.in);
void read()
{
a=sc.nextInt();
b=sc.nextInt();
}
}
class Add extends Read
{
void add()
{
read();
c=a+b;
System.out.println("Addition is "+c);
}
}
class Sub extends Read
{
void sub()
{
read();
c=a-b;
System.out.println("subtraction is "+c);
}
}
class Mul extends Read
{
void mul()
{
read();
c=a*b;
System.out.println("Multiplication is "+c);
}
}
class Div extends Read
{
void div()
{
read();
c=a/b;
System.out.println("Division is "+c);
}
}
class Arithmetic
{
public static void main(String[] anand)
{
Add oa=new Add();
oa.add();
Sub os=new Sub();
os.sub();
Mul om=new Mul();
om.mul();
Div od=new Div();
od.div();
}
}

Multilevel Inheritance: Whenever multiple classes are participated in inheritance in sequential


order is called multi level inheritance.
SUPER-CLASS
A
EXTENDS

SUB-CLASS
B
EXTENDS

C SUB-SUBCLASS

Example: As mentioned, it is perfectly acceptable to use a subclass as a superclass of another.


For example, given three classes called A, B, and C, C can be a subclass of B, which is a
subclass of A. When this type of situation occurs, each subclass inherits all of the traits found in
all of its superclasses. In this case, C inherits all aspects of B and A. To see how a multilevel
hierarchy can be useful, consider the following program.
// Create a super class.
class A {
A() {
System.out.println("Inside A's constructor.");
}
}
// Create a subclass by extending class A.
class B extends A {
B() {
System.out.println("Inside B's constructor.");
}
}
// Create another subclass by extending B.
class C extends B {
C() {
System.out.println("Inside C's constructor.");
}
}
class CallingCons {
public static void main(String args[]) {
C c = new C();
}
}
The output from this program is shown here:
Inside A’s constructor
Inside B’s constructor
Inside C’s constructor

Hybrid Inheritance: It is a combination of one or types of other inheritances.


Member access rules:

Java provides many levels of protection to allow fine-grained control over the visibility of
variables and methods within classes, subclasses, and packages.
Classes and packages are both means of encapsulating and containing the name space and scope
of variables and methods. Packages act as containers for classes and other subordinate packages.
Java addresses four categories of visibility for class members:
• Subclasses in the same package
• Non-subclasses in the same package
• Subclasses in different packages
• Classes that are neither in the same package nor subclasses

Access within within outside package by outside


Modifier class package subclass only package

Private Y N N N

Default Y Y N N

protected Y Y Y N

Public Y Y Y Y

We can protect the data from unauthorized access. To do this ,we are using access specifiers.
An access specifier is a keyword that is used to specify how to access a member of a class or the
class itself. There are four access specifiers in java:
private: private members of a class are not available outside the class.
public: public members of a class are available anywhere outside the class.
protected: If you want to allow an element to be seen outside your current package, but only to
classes that subclass your class directly, then declare that element protected.
default: if no access specifier is used then default specifier is used by java compiler.
Default members are available outside the class. Specification, it is visible to subclasses as well
as to other classes in the same package. This is the default access.
Note: A non-nested class has only two possible access levels: default and public.
When a class is declared as public, it is accessible by any other code. If a class has default
access, then it can only be accessed by other code within its same package. When a class is
public, it must be the only public class declared in the file, and the file must have the same name
as the class.
Example For Private:

class A{

private int data=40;

private void msg()

System.out.println("Hello java");

public class Simple{

public static void main(String args[]){

A obj=new A();

System.out.println(obj.data);//Compile Time Error

obj.msg();//Compile Time Error

}
Example for default:

//save by A.java

package pack;

class A{

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();//Compile Time Error

obj.msg();//Compile Time Error

Example for Protected:

//save by A.java

package pack;

public class A{

protected void msg(){System.out.println("Hello");}

//save by B.java
package mypack;

import pack.*;

class B extends A{

public static void main(String args[]){

A obj = new A();

obj.msg();

Example for public:

//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();

}
}

super keyword:

super is a keyword in java language represents super class(or) base class object.

super keyword can be used in two different ways

1.super.

2.super()

Super.:

class Nagarjuna

void property()

System.out.println("I have 30 cars");

class Akhil extends Nagarjuna

void property()

super.property();

System.out.println("I have 20 bikes");

public static void main(String[] args)

Akhil oa=new Akhil();

oa.property();

}
}

super():

When ever we want to call base class constructor with in the derived class constructor then super() can be
used

Syntax:

super() used to call no parameterized constructor of super class in to derived class constructor

super(value1,value2---)used to call parameterized constructor of base / super class into sub/derived class
constructoer

class SuperEx

SuperEx()

System.out.println("This is super class");

class SubEx extends Super

SubEx()

super();

System.out.println("This is sub class");

public static void main(String[] args)

SubEx s2=new SubEx();

}
Preventing Inheritance:

To prevent the inheritance in java we use the keyword final.

final: final keyword in java used restrict the inheritance. The java final keyword can be used in
many context. Final can be:

1. variable
2. method
3. class

The final keyword can be applied with the variables, a final variable that have no value it is
called blank final variable or uninitialized final variable. It can be initialized in the constructor
only. The blank final variable can be static also which will be initialized in the static block only.
We will have detailed learning of these. Let's first learn the basics of final keyword.

final class A

final void show()

System.out.println("This is show()");

class B extends A //Error occured

void showmsg()

System.out.println("Hello");
}

If you compile the above program we will get the error because class A is declared as final.

class Vehicle{

void run()

System.out.println("It is running...");

final void shape()

System.out.println("It has good shape…");

class Bike extends Vehicle{

public static void main(String args[]){

Bike i=new Bike();

i.run();

i.shape();//Error

If you compile the above program we will get the error because method run is declared as final.
Base class Object or The Object class:

Object class: Super class for all the classes in java including user defined classes directly or
indirectly.
Importing Object class: Java API
Java.lang package
Object class
Object class is implicitly(automatically) imported into our source code, because it is in “lang”
package. Lang package is also implicitly imported into every java program.
Object class reference can store any reference of any object. This means that a reference variable
of type Object can refer to an object of any other class.
Advantage: When we want to write a method that needs to handle objects if unknown type. If we
define a parameter of object type, any class object can be passed to the method. Thus the method
can receive any type of object and handle it.

Method Description
boolean This method compares the references of two objects and if they are equal,
equals(Object obj) it returns true, otherwise false.
String toString() This method returns a string representation of an object.
Class getClass() This method gives an object that contains the name of a class to which an
object belongs. Obtains the class of an object at run time.
int hashCode( ) Returns the hash code associated with the invoking object. This method
returns hash code number of an object.
void notify( ) This method sends a notification to a thread which is waiting for an
object.
void notifyAll( ) This method sends a notification for all waiting threads for the object.
void wait( ) This method causes a thread to wait till a notification is received from a
notify() or notifyAll() methods.
Object clone( ) This method creates a bitwise exact copy of an existing object. Creates a
new object that is the same as the object being cloned.
void finalize( ) Called before an unused object is recycled. This method is called by the
garbage collector when an object is removed from memory.

Note: The methods getClass( ), notify( ), notifyAll( ), and wait( ) are declared as final. You may
override the others.
Example programs:
Example program for equal():
import java.io.*;
import java.util.*;
class Myclass
{
int x;
Myclass(int x)
{
this.x=x;
}
}
class Compare
{
public static void main(String args[])
{
Myclass obj1=new Myclass(15);
Myclass obj2=new Myclass(15);
Integer obj3=new Integer(15);
Integer obj4=new Integer(15);
if(obj1.equals(obj2))
System.out.println("obj1 and obj2 are same");
else
System.out.println("obj1 and obj2 are not same");
if(obj3.equals(obj4))
System.out.println("obj1 and obj2 are same");
else
System.out.println("obj1 and obj2 are not same");
}
}
Output: obj1 and obj2 are not same
obj1 and obj2 are same
Forms of inheritance:

Inheritance is used in a variety of way and for a variety of different purposes .


• Inheritance for Specialization

• Inheritance for Specification

• Inheritance for Construction

• Inheritance for Extension

• Inheritance for Limitation

• Inheritance for Combination One or many of these forms may occur in a single case.
Specialization:
Most commonly used inheritance and sub classification is for specialization.
Always creates a subtype, and the principles of substitutability is explicitly upheld.
It is the most ideal form of inheritance.
An example of subclassification for specialization is;
public class PinBallGame extends Frame {
// body of class
}
Specification:

This is another most common use of inheritance. Two different mechanisms are provided by
Java, interface and abstract, to make use of subclassification for specification. Subtype is formed
and substitutability is explicitly upheld. Mostly, not used for refinement of its parent class, but
instead is used for definitions of the properties provided by its parent.

class FireButtonListener implements ActionListener

// body of class

class B extends A

// class A is defined as abstract specification class

Construction:
Child class inherits most of its functionality from parent, but may change the name or parameters
of methods inherited from parent class to form its interface. This type of inheritance is also
widely used for code reuse purposes. It simplifies the construction of newly formed abstraction
but is not a form of subtype, and often violates substitutability.

Example is Stack class defined in Java libraries.

Extension:

Subclassification for extension occurs when a child class only adds new behavior to the parent
class and does not modify or alter any of the inherited attributes.

Such subclasses are always subtypes, and substitutability can be used.

Example of this type of inheritance is done in the definition of the class Properties which is an
extension of the class HashTable.

Limitaion:
Subclassification for limitation occurs when the behavior of the subclass is smaller or more
restrictive that the behavior of its parent class. Like subclassification for extension, this form of
inheritance occurs most frequently when a programmer is building on a base of existing classes.
Is not a subtype, and substitutability is not proper.

Combination:

This types of inheritance is known as multiple inheritance in Object Oriented Programming.


Although the Java does not permit a subclass to be formed be inheritance from more than one
parent class, several approximations to the concept are possible.
Example of this type is Hole class defined as;
class Hole extends Ball implements PinBallTarget{
// body of class
}
Abstract classes and methods:

In java language abstract is a keyword represents incomplete .

While inheriting a concrent class is inherited in any other class out the properties of base class
are extended into derived class so that we can achive reusability but in same clases we want re
use same method in multiple derived class with seperete body part at that time the body part of
base class method (overridden method) will be wasted (or) misused to overcome this problem we
can use abstract classes.

If any class is incomplete then that can be declared as abstract class.

Abstract method:

If any method contains only signature with no body part is known as abstract method

Syntax:

abstract returntype methodname(lp/n/p);

If any class contains at least one abstract method that class becomes “abstract class”

Abstract class can contain any no of abstract methods

Example for Abstract Methods and Classes:

abstract class Animal

public void eat()

System.out.println("This animal eat everyday");

public void sleep()

System.out.println("This animal sleep everyday");

public abstract void sound();

class Cat extends Animal

{
public void sound()

System.out.println("This animal make sound like miaaww...");

class Dog extends Animal

public void sound()

System.out.println("This animal make sound like Bowwwww...");

class Gri

public static void main(String args[])

Cat oc=new Cat();

System.out.println("===this is Cat Animal========");

oc.eat();

oc.sleep();

oc.sound();

Dog od=new Dog();

System.out.println("===this is Dog Animal========");

od.eat();

od.sleep();
od.sound();

Output:

===this is Cat Animal========

This animal eat everyday

This animal sleep everyday

This animal make sound like miaaww...

===this is Dog Animal========

This animal eat everyday

This animal sleep everyday

This animal make sound like Bowwwww...

In above example Animal is a base class is having sound() is a abstract method with no
implementation because all animals eat every day and sleep everyday but make sound is
different.So here sound() is declared as abstract method now its sub classes implement their own
implementation by overriding it.

Disadvantages are following in abstract class:

1.Irrespective of usage every abstract method should be overridden in the derived class.

2.multiple inheritance is not supported at class level .(multiple abstract class properties can’t be
reused at a time in other classes)

3.by making a class as an abstract we are missing class properties (or) class features.

Polymorphism:
If any element is existing multiple times in different forms is known as polymorphism
(polymorphism represents many number of forms)

In java language polymorphism can be achived using methods


Definition:
With same method name is existing multiple times to performs multiple opearations is known a
polymorphism.

Polymorphism two types

1.Ad-hoc polymorphism

2.Pure polymorphism

Ad-hoc polymorphism:

Ad-hoc polymorphism is obtained when a function works, or appears to work, on several


different types (which may not exhibit a common structure) and may behave in unrelated ways
for each type. Method overloading is the best way to express the ad-hoc polymorphism.

Method Overloading:

If a class has multiple methods having same name but different in parameters, it is known
as Method Overloading.

If we have to perform only one operation, having same name of the methods increases the
readability of the program.

Suppose you have to perform addition of the given numbers but there can be any number of
arguments, if you write the method such as a(int,int) for two parameters, and b(int,int,int) for
three parameters then it may be difficult for you as well as other programmers to understand the
behavior of the method because its name differs.

Method Overloading is done in following ways

Different order of parameters

Different types of parameters

Different number of parameters


class Person
{
void walk()
{
System.out.println("I am walking");
}
void walk(String name)
{
System.out.println("I am "+name+" walking");
}
void walk(String me,String friend)
{
System.out.println("I am "+me+" and my friend "+friend+" are walking");
}
public static void main(String[] args)
{
Person p=new Person();
p.walk();
p.walk("Anand");
p.walk("Anand","Teja");
}
}
Pure polymorphism:
This type of polymorphism occurs when a polymorphic variable is used as an argument.
Different effects are formed by using different types of value
class StringBuffer
{
String append (Object value)
{
return append(value.toString());
}
... }
Different objects implement toString differently so the effects will vary depending upon the
argument.
A polymorphic variable is a variable that canreference more than one type of object
Polymorphic variables derive their power from interaction with inheritance, overriding and
substitution.
A common polymorphic variable is the implicit variable that maintains the receiver during the
execution of a method.
Downcasting is the undoing of a polymorphic assignment.
Pure polymorphism occurs when a polymorphic variable is used as an argument.
Method Overriding:
If subclass (child class) has the same method as declared in the parent class, it is known as
method overriding in java.

If base class is derived in derived class the derived class method overrides the base class method
whenever both the method are existing with same name and same signature .so that the derived
class overriding method called when ever we are accessing same method name with derived
class object

Rules for Java Method Overriding:

method must have same name as in the parent class

method must have same parameter as in the parent class.

must be IS-A relationship (inheritance).


class Vehicle

void run()

System.out.println("Vehicle is running");

class Bike2 extends Vehicle

void run()

System.out.println("Bike is running safely");

public static void main(String args[])

Bike2 obj = new Bike2();

obj.run();

You might also like