Sie sind auf Seite 1von 18

1

Base-Camp Notes:The Java Platform


Before understanding what the Java platform is and how it enable programs written in
Java to be machine independent, let us see how to write and execute a program written in
any high level language. The programs written using such languages (also called as the
source code) are usually, entered using a text editor. Then, a compiler or an interpreter is
used to check the program for errors and translate it into the machine language of the
computer being used. This translate version is also called as the Object code or
executable. In the case of non-machine independent languages, the object code created is
specific to the computer being used and can be executed only by that computer.
In Java, when a program is compiled, instead of a machine-dependent object code, an
object file with Bytecodes is created. Bytecodes are the basic instruction that can be
executed only by the Java Virtual Machine (JVM). The JVM, in turn translate the byte
codes into a version that can be executed by the actual machine. So, a Java program
written on any computer can be run on any other computer on which JVM has been
installed. The JVM has to be implemented separately for every type of the machine.
Today the JVM is already available for a wide variety of popular machine types. The
JVM is usually another piece of software that is installed on the machine. However, there
are serious efforts to make a chip that uses the byte codes as the basic instructions.
Another important component that is used with the JVM is the Java Application
Programming Interfaces (APIs). The API is a collection of complied code that can be
include in the Java programs you write. They help you to see time by providing you with
several ready-made solutions for tasks that need to be frequently performed. The JVM
and APIs together are referred to as the Java program.
Java Applications and Applets
Programs in Java can be of two types. They are
1. Applications
2. Applets
An application is a Java program that can be run on your computer, using the JVM you
have installed on it. They are like computer programs written using any other high level
language.
A Java applet is a Java program that typically needs a web browser or execution. The
browser has an inbuilt JVM that helps in executing these applets. The applets can also be
tested using a utility available as part of JDK- the applet viewer.
Let us take a moment to understand the need and use of applets. The main reason that is
so popular today is because it can be used on the Internet. The WWW is huge collection 0
millions of pages containing information about practically any topic that you can think of.
These pages can be created using a language called the Hyper Text Markup Language
(HTML). Java applets can be embedded in these pages to add sound, animation and
multimedia effects. A good example to illustrate the application of applets is the e-cards
that are available free on several sites.

2
In this Lesson, we will see how to write Java applications (also called as java programs).
You will learn more about applets in later Lessons.
Java Developers Kit (JDK)
Java Developers Kit (JDK) is a collection of tools an necessary documentation for
making Java application and applets. The JDK consists of
-

the Java compiler javac.exe to convert Java programs into bytecodes.


The Java interpreter java .exe to translate bytecodes into program action to be
executed by the JVM.
The Java debugger jdb.exe to debug Java programs.
The Java disassembler javap.exe to display certain specific interfaces.
The Java header file generator javah.exe
The Java documentation javaDoc.exe
Applet viewer.

The Java Source Developers Kit, SDK 1.22 supports the latest version of Java 2. This is
an extension of the latest Java Developers Kit 1.2.
Object, Classes and Methods
Java is an object oriented programming language. As the name indicates, object are the
fundamental units of such programming languages. Every object has a state and behavior
associated with it. The state of the object is the variables and constants associated with
the object. Behavior is the actions that can be performed by the object. This behavior is
represented in programs by a sequence of statements that perform a specific task. They
are also known as Methods. So, objects consist of constants, variable and methods. At a
higher level, every object is created from a prototype called class.
These concepts can be very confusing initially. But let us to understand them better with
an example.
Have you played with building blocks? They are small pieces of different shapes and
colours that can be fitted together to form shapes. Let us say, we have a set of 100 plastic
building blocks. Such a set would typically have blocks of different colours and size. To
builds shapes, all you would have to do is to pick up unused block of the right size and
colour and fit them together.
In this example, the complete set of blocks is the class. The blocks the set will have some
features that are common- they are all toys made of plastic. Hence they are grouped
together as a class, the building block set.
The individual blocks, in the example, are the objects. As mentioned above, each of these
will have some features which are common to all the other blocks in the group. But they
will also have other features that are unique to them, for example, their color and size.

3
But, that is not all. To build a structure with these blocks, we need to know if the block is
unused or not. A method can be written to give us this information.

History of Java
Java was developed by Sun Microsystems. The origin of Java can be traced back to a
project called the Green Project at Sun Microsystems in year 1991. The Java
development team included James Gosling (Chief programmer), Patrick Naughton and
Mike Sheridan. The basic idea behind the project was to develop a platform independent
software technology that should have a low cost of maintenance and should not have the
complicated features of C++ language (Feature such as pointers, memory management,
multiple inheritance, etc.). The development team named the new language as Oak. Later,
it was renamed Java.
In the year 1994, the Java technology was applied to the Web for the first time. As World
Wide Web (WWW) grew dramatically, people with different and operating systems
started accessing the applications available on the Web. Since Java provided the required
cross platform independence, i.e., independence from the hardware and the operating
system, very soon it became the integral part of the Web.
Java software works just about everywhere, from the smallest devices to supercomputers.
Java programs do not depend on the kind of the computers or the operating systems they
run on. They work on any kind of compatible device that support the Java platform.

Features of Java
Sun Microsystems listed h features of Java as follows:
Simple: Java is a simple programming language that can be learned easily. The syntax is
similar to C++ but it does not involve complex features like of C++. In Java, memory
management is automatically implemented by the concept of garbage collection.
Object-Oriented: Java is an object oriented programming language that provides
features such as polymorphism, abstraction, inheritance and encapsulation. These features
make Java programs flexible to changes, easy to maintain and to reuse the code in an
efficient way.
Distributed: Java can be used develop distributed applications that can access data
across the Web as easily as they access data from a local system.
Interpreted, Robust, Secure, Architecture Neutral, Portable, High Performance,
Multithreaded, Dynamic.

4
What is Bytecodes
A java program can be written in any text editor. The file stored with an extension .java.
The program is compiled and checked for syntactic errors. It the program is error free, it
creates another file with the extension .class based on the .java file. The content of a
.class file id called the bytecode.
Bytecodes are platform independent and can be executed on machines which has
any version of java interpreter installed.
The bytecode generated by Java Development Kid (JDK) of one platform can be
used to run on the other platforms in which the respective version of JDK is
available.
Bytecodes are interpreted in order to get the output.
JVM
The JVM is the heart of java network orientation. It acts as an interface between the java
applications and the hardware systems. The .class files of java API are loaded into the
JVM, interpreted and executed. All java programs interact only with the JVM and can
therefore, are executed on any machine that hosts the JVM.
The JVM and the Java API are built for every platform. The Java program calls the
methods of the Java API, which invokes the methods of the underlying operating system.
Platform Independent Features:Java is platform independent. The meaning of platform here may be confusing for us but
actually this word is poorly defined. In the computer industry it typically means some
combination of hardware and system software but here we can understand it as our
operating system.
Java is compiled to an intermediate form called Java byte-code or simply byte code. A
java program never really executes immediately after compilation on the host machine.
Rather, this special program called the java interpreter or Java Virtual Machine reads the
byte code, translates it into the corresponding host machine instructions and then
executes the machine instructions. A java program can run on any computer system for
which a JVM and some library routines have been installed. The second important part,
which makes the java portable, is the elimination of hardware architecture dependent
constructs. For example, we can write and compile the java program on window 98 and
execute the compiled program on JVM of the Macintosh operating system.
How JAVA works ?
Ans.: A compiler converts the java program into an intermediate language representation
called Bytecode which is platform independent. A java file will have extension .java, like
word file has .doc, text file has the .txt extension.
The concept of write once, run anywhere is possible in java. The Java program can be
complied on any platform having a java compiler. The resulting bytecodes can then be
run on Windows 98, Windows 2000 or Solaris or Macintosh or any other machine. The
machine should have a Java platform to run Java code. Java platform consists of Java
Virtual Machine (JVM) and a package of ready-made software components. This
package is known as the Java Application Programming Interface (Java API). The
compiled java program can run on any hardware platform having Java Virtual
Machine(JVM) install on it.

5
How you compile java program?
Ans.: Write the following program named firstClass.java through edit and save it to
jdk1.3/bin directory.
1. import java.io.*;
public class firstClass {
public static void main(String args[]) {
System.out.println("Hi ! This is my First Program in Java") ;
}
}
2. c:\jdk1.3\bin> javac firstClass.java
javac will convert it to bytecode. Then you find firstClass.class
3. c:\jdk1.3\bin>java firstClass
Array
Arrays are a means of storing a list of items. Multiple values of the same type can be
stored together. Arrays can hold data of similar type.
To use an array we require the following to be done.
Declare a variable to be used as the array name.
Create an array object and assign to the variable.
int values[]=new int[10];
This creates an array with the name values, the type of the values stores in integer and the
number of elements that can be store in the array is 10. This is also called dimension of
the array. When the array is created initially all the values are initialized to zero. The
individual elements of the array can be access by using an index with the array name.
For example the first element of the above array is referred as values[0], second element
is referred as values[1] and so on.
Arrays can contain any legal java data type including reference types such as objects or
other arrays. For example, the following declares an array that can contain ten String
objects.
String[] str1 = new String[10];
Or
String str1[] = new String[10];
Creating and initialization of an array can be done at the same time as follows:
int[] values=new {5,6,7,8,9,10};
Two dimensional arrays are used as follows.

6
int[][] myArray = new int[5][5];
What is static?
Ans.: There will be times when we will want to define a class member that will be used
independently. A class member must be accessed only in conjunction with an object.
However, it is possible to create a member that can be used by itself, without reference to
a specific instance. To create such a member, precede its declaration with the key static.
When a member declare static, it can be accessed before any objects of its class are
created, and without reference to any objects. We can declare both member and variables
to be static. The most common example of a static is main(). main() is declare as static
because it must be called before any objects exist.
Instance variables declared as static are, essentially, global variables. When
objects of its class are declared, no copy of static variable is made, all instance of the
class share the same static variable.
Methods declared as static have several restrictions:
They can only call other static methods
They must only access static data.
They cannot refer to this or super in any way(The keyword super relates to
inheritance)
Constructor Methods
Constructor method is called when an object is created. Constructor methods are called
automatically by java. Constructor methods are written keeping the following points in
mind.
There can be more than one constructor method. But the number or type of
arguments have to be different.
Constructor methods have the same name as the name of the class.
Typically they are used as to set initial values to instance variables.
Overloading Methods
You can have same name for more than one method. The number of arguments or the
type of arguments are to be different for creating two or more methods with the same
name. The return types of the methods can be different as long as the method signature is
different. The example below shows overloading of a method called add. The first add()
takes integers as arguments and returns the sum as floating point number. The second
add() takes floating point numbers as arguments and returns the sum as a floating point
number. The third ass() takes string as arguments, converts them to integer add then
return sum as floating point number. The program below shows overloading of methods.
Subclasses/Inheritance/Super class/Extends
When more than one let us say Class1 and Class2 have some properties to be shared, then
they could be defined in a single class let us say Class0 as if they belonged to themselves.
Here Class1 and Class2 are called subclasses and Class0 is called as super class . The

7
keyword extends is used after the name of class. The keyword extends is followed by
the name of the super class. The concept of using methods and variables defined in
another class is called as inheritance. In java only single inheritance is allowed that
means classes can inherit methods only form one intermediate super class. Inheritance
provides a chain in which a class inherits not only from its immediate super class, but
also super class upwards.
Method overriding
When an objects method is called, java looks for the method definition in the objects
class. If it can not find, then it checks one level up in the hierarchy of classes. Consider
the cause when the same method name is used in both the subclass and superclass with
the same signature (same number of argument with the type) . Here when the method is
called, method defined in the subclass is invoked. The method defined in the super class
is overridden. It is now hidden for the objects of the subclass. If the method in the super
class has to be used, then the super keyword can be used along with the name of the
method. In the example the method display() and this.display() will invoke method
display() of the superclass.
Final class, methods and variables
The final modifier indicates that the entity can not be changed.
A final class can not be subclassed.
A final method cannot be overridden
A final variable cannot change its value.
Variables are declared as final when their values does not change. They are also defined
as static since the constant values in a class will be generally classwide information.
Final methods run efficiently. Java class library declares many of the commonly used
methods final so that they can be executed more quickly.
A final class cannot be subclassed by another class. This gives some speed benefits.
Many popular java classes such as java.lang,Math, java.lang.String are final. All methods
in a final class are automatically final.
Abstract Classes
When the keyword abstract appears in a class definition, it means that zero or more of its
methods are abstract. An abstract method has no body. Some of the subclass has to
override it and provide the implementation. Objects cannot be created out of abstract
classes. Abstract classes basically provide a guideline for the properties and methods of
an object. In order to use abstract classes, they have to be subclassed. If all the methods
in the abstract classes are abstract that is without any implementation, then it is better to
implement as an interface than as an abstract class.

Exception Handling
The java language uses exceptions to provide error-handling capabilities for its programs.
An exception is an event that occurs during the execution of a program that disrupts the
normal flow of instructions. It is basically a shorthand to indicate exceptional event.
When such an event occurs within a Java method, the method creates an exception object
and hands it off to the runtime system. The exception object contains information about
the exception, including its type and the state of the program when the error occurred.
The runtime system is then responsible for finding some code to handle the error. In java
terminology, creating an exception object and handing it to the runtime system is called
throwing an exception.
By using exceptions to manage errors, java programs have the following advantages over
traditional error management technique.
1. It helps to separate the error handling code from the regular code.
2. The runtime system searches back words through the call stack, beginning with
the method in which the error occurred, until it finds a method that contains an
appropriate exception handler. A java method can duck any exceptions thrown
within it, thereby allowing a method further up the call stack to catch it. Thus
only the methods that care about errors have to worry about detecting errors.
3. Grouping or categorization of exceptions is possible.
Types of Exception :1. Checked Exception : These types of exceptions are checked during
compilation of the program. Such exceptions are presumed because their
occurrence can be due to some other faulty process.
Eg. IOException, ClassNotFoundException, InterruptedException etc.
2. Unchecked Exception : These types of exceptions are checked during
execution of the program. Such exceptions cannot be presumed because
they may occur due to runtime error in a program.
Eg. NumberFormarException, ArithmeticException etc.
Build In Exception:
Exception
ArithmeticException
ArrayIndexOutOfBoundsException
FileNotFoundException

Description
Arithmetic errors.
Array Index out of bound
Reference to a file that cant be found .

IOException
IllegalArgumentException
InterruptedException

Caused by general IO failure.


Calling a method with an improper
argument.
Caused by time interval in thread.

IndexOutOfBoundsException

A string out of bounds.

9
NullPointerException
NumberFormatException
StringIndexOutOfBouds

Reference to an object that has not been


instantiated.
Invalid conversion of a string to a numeric
format.
Attempt to index outside the bounds of
string

File Stream:
A stream is a path traveled by data in a program. To bring in
information, a program opens a stream on an information source( a
file, a memory, a socket) and reads information .
Similarly ,a program can send information to an external destination by
opening a stream to be a destination and writing information out
serially.
Using a Stream:
No matter where the information is coming from or going to and no matter what type of
data is being read or written, the algorithms for reading and writing data remain the same.
The steps involved are.
Create an object of input/output stream that is associated with the data source/data
destination.
Read/write data using the objects read()/write() methods.
Finally close the stream by calling close() method.
The java.io package contains a collation of stream classes for doing this. These classes
are divided into two class hierarchies based on the data type on which they operate. They
are byte streams and character streams.

Predefined Streams:
There are three predefined streams already open and ready to use in every program.
These streams are declared in the java.lang.System class, and they are all byte streams.
a) a) System.in: This is the standard InputStream. This stream is already open
and ready to supply input data. Typically this stream corresponds to keyboard
input.
b) b) System.out : The standard PrintStream. This stream is already open and
ready to accept output data. Typically this stream corresponds to display output.

10
c) c) System.err : The standard error output stream. This stream is already open
and ready to accept output data. Typically this stream corresponds to display
output.

Data Streams
Data Input Stream and Data Output Stream
If you need to work with data that is not represented as bytes or
characters, you can use dada input and data output streams. These
streams filter an existing byte stream so that each of the following
primitive types can be read or written directly from the stream :
Boolean, byte, double, float , int, long and short.
A data input stream is created with the DataInputStream(InputStream)
constructor. The argument should be existing input stream such as a
buffered input stream. Conversely, a data output stream requires the
DataOutputstream(Output Stream) constructor, which indicates the
associated output stream.
Some features of Stream:
length()
- count number of character of string
charAt(int)
- Returns a charter from a string at nth position.
compareTo(Object)
- Returns 0 if equal.
compareTo(String)
- Returns 0 if equal.
substring(int,int) - Give the starting position, ending position.
toUpperCase()
-Return to block letter of a string.
toLowerCase()
-Return to lowercase of a string.

Thread
A thread is similar to a program that has a single flow of control.
Multithreading is a conceptual programming paradiagram where a program is divided
into two or more subprogram, that can be implemented at the same time in parallel.
Some important methods of thread:1.
start() : it is used to start the execution of thread body. It is define in the run()
method.
2.
stop() : used to stop the execution of thread, no matter what the thread is doing.
3.
suspend() : it is use to temporarily stop the execution of the thread. All states and
resources of the thread retain intact.
4.
resume() : use to resume the suspended thread will be scheduled to run.
5.
sleep(millisec.) : used to sleep the current thread for minimum of specified time
period.
6.
join() : used for the caller thread to wait for this thread to die.
Life cycle of thread :1. Newly created thread : A thread enters the newly created state immediately after
creation. In this state local data members are allocated and initialized, but execution
of the run() method will not begin until its start() method is called.

11
2. Runnable thread : when the thread is in the runnable state the execution context
exists and the thread can be scheduled to run at any time.
3. Blocked thread : the blocked state is entered when one of the following state occurs :
a.
b.
c.
d.
e.

The thread itself or another thread calls the suspend().


The thread calls an wait().
The thread itself calls the sleep().
The thread is waiting for some input/output operations to itself.
The thread will join another thread.

A thread will return back to the runnable state when the following event occurs:
a. If the thread is suspended another thread calls resume().
b. If the thread is blocked by calling an wait(), the notify() method is called.
c. If the thread is blocked on IO, the specified IO operations completes.
4. Dead thread : the dead thread is entered when a thread finishes its execution or is
stopped by another thread calling its stop(). To find out whether a thread is alive it
uses threads isAlive().

Start()

Newly
created
thread

Stop(), run() ends

Suspend(), wait(), sleep(),


IOBlocking
Runnable
Blocked

Stop(),
run() ends

resume(), notify(),
sleepTimeOut(),
IO finished
Stop(), run() ends

Dead
Thread life cycle
Synchronization :It is the way to avoid data corruption caused by simultaneous access to the same data
because all the threads in a program share the same memory space, it is possible for two
threads to access the same variable at the same time. Problems may occur when multiple
threads are accessing the same data concurrently. Threads may race to each other and one
thread may overwrite the data just written by another thread and break the consistency of
the data.
For that some mechanism is needed to block one threads access to the critical data if the
data is being worked on by another thread.
Thread priority :In java, each thread is assigned a priority, which affects the order in which it is scheduled
for running. The threads are of the same priority. The threads of the same priority are

12
given equal treatment by the java scheduler and therefore they share the processor on a
first-come, first-serve basis.
Java permits us to set the priority of a thread using the setPriority() method as
follows :
ThreadName.setPriority(intNumber);
The intNumber is an integer value to which the threads priority is set. The thread class
defines several priority constants:
MIN_PRIORITY = 1
NORM_PRIORITY = 5
MAX_PRIORTY = 10
The intNumber may assume one of these constants or any value between 1 and 10.

Package :Packages are javas way of grouping a varity of classes and interfaces together. The
grouping is usually done according to functionality. In fact package acts as a containers
for classes. Package has the following benefits :
1.
The classes contained in the packages of other programs can be
easily reused.
2.
In packages, classes can be unique compared with classes in
other packages.
3.
Package provides a way to hide classes thus preventing other
programs or packages from accessing classes that are meant for internal use only.
4.
Packages also provide a way for separating design from
coding.
5.
It is possible to change the implementation of any method
without affecting the rest of the design.

Applet :Applets are small java program that are primarily use in Internet computing. They can be
transported over the Internet from one computer to another computer and run using the
appletviewer or any other web browser that supports java. It can perform arithmetic
operation, display graphics, play sounds, accept user input, creates animation and play
interactive games.
Applet life cycle :-

Begin
( Load Applet )

Born

Initialization

start()

stop()
Running

Display
paint()

Idle

Stopped

start()
Destroyed

Dead
Exit of Browser
destroy()

End

13
1.

Born or Initialization state :- Applet enters the initialization state when it is


first loaded. This is achieved by calling the init() method of Applet class. It
does the following job.
a. Create objects needed by the applet
b. Set up initial values
c. Load images or fonts
d. Set up colors
The initialization occurs only once in the applets life cycle.

2.

Running State :- Applet enters the running state when the system calls the
start() method of applet class. This occurs automatically after the applet is
initialized. The start() method may be called more than once.

3.

Idle or stopped state :- an applet becomes idle when it is stopped from


running. Stopping occurs automatically when we leave the page containing
the currently running applet. We can also call the stop() explicitly.

4.

Dead or destroy state :- Applet is said to be dead when it is removed from


memory. This occurs automatically by invoking the destroy() method when
we quit the browser. It occurs only once in the applets life cycle.

5.

Display state :- Applet moves to the display state whenever it has to perform
some output operations on the screen. The paint() is called to accomplish this
task.

Local Applet : An applet developed locally and stored in a local system is known as a
local applet. It does not need to use the Internet and therefore the local system does not
require the Internet connection. It simply searches the directories in the local system and
locates and loads the specified applet.
Remote Applet : A remote applet is that which is developed by someone else and stored
on a remote computer connected to the internet. If our system is connected to the Internet,
we can download the remote applet onto our system via the Internet and run it.
How applet differ from Applications: Applet do not use the main() method for initiating the execution of the code.
Unlike stand-alone application, Applet cannot run independently. They are run
through HTML code.
Applet cannot read from and write to the files in the local computer.
Applet cannot communicate with other servers on the network.
Applet cannot run any program from the local computer.
Applets are restricted from using libraries from other languages such as C or C++.

14
Drawing methods of Graphics class :1. drawLine(x1,y1,x2,y2) : to draw a line from x1,y1 coordinate to x2,y2
coordinate.
2. drawRect(x,y,width,height) : to draw a rectangle from x,y coordinate with given
width and height.
3. drawRoundRect(x,y,width,height,corner_angle1,corner_angle2) : to draw
rectangle with rounded edges.
4. drawOval(x,y,width,height) : to draw oval and circle shapes.
5. drawArc(x,y,width,height,starting_angle,sweep_angle) : Zero baseline starts
from right and rotate anticlockwise.
6. drawPolygon(x[],y[],n_points) : array of x coordinate, array of y coordinate and
number of points.
Different shapes fill with colors :Use g.setColor(Color.red) method to make fill color.
7. fillRect(x,y,width,height) : to draw a rectangle from x,y coordinate with given
width and height.
8. fillRoundRect(x,y,width,height,corner_angle1,corner_angle2) : draw rectangle
with rounded edges.
9. fillOval(x,y,width,height) : to draw oval and circle shapes.
10. fillArc(x,y,width,height,starting_angle,sweep_angle) : Zero baseline starts from
right and rotate anticlockwise.
11. fillPolygon(x[],y[],n_points) : array of x coordinate, array of y coordinate and
number of points.
Some important terms :
Transient modifiers : when an instance variable is declared as
transient, then its value need not persist when as object is stored. For eg. transient
int a;

Volatile modifiers : the volatile modifier tells the compiler that


the variable that it modifies can be changes unexpectedly by other parts of our
program. In multithreaded program, sometimes two or more threads will share the
same instance variable.

Intanceof operator : sometimes it is useful to know the type of an


object during run time. If object is of the specified type or can be cast into the
specified type, then instanceof operator evaluates to true otherwise false. For eg.
Class A{
int i,j;
}
class B extends A{
int k;
}
class Main_Class
{
public static void main(String args[])
{

15
A a=new A();
B b=new B();
if(a instanceof A)
System.out.println(a is instance of A);
if(c instanceof A)
System.out.println(c can be cast to A);
}
}

Garbage Collection : Since objects are dynamically allocated by using the new
operator, we might be wondering how such objects are destroyed and their
memory released for later reallocation. Java handles deallocation for us
automatically. This technique is called garbage collection.
Finalize() method : Sometimes an object will need to perform some action when
it is destroyed. For eg. if an object is holding some non-java resource such as a
file handle or window character font, then we might want to make sure these
resources are freed before an object is destroyed. To handle such situation java
provides a mechanism called finalization. Right before an assets is freed, the java
run time calls the finalize() method on the object. The finalize() method only
approximates the function of a destructor.

Introducing Nested and Inner Classes


It is possible to define a class within another class; such classes are known as nested
classes. The scope of a nested class is bounded by the scope of its enclosing class. Thus,
if class B is defined within class A, then B is known to A, but not outside of A. A nested
class has access to the members, including private members, of the class in which it is
nested. However, the enclosing class does not have access to the members of the nested
class. There are two types of nested classes: static and non-static. A static nested class is
one which has the static modifier applied. Because it is static, it must access the members
of its enclosing class through an object. That is, it cannot refer to members of its
enclosing class directly. Because of this restriction, static nested classes are seldom used.
The most important type of nested class is the inner class. An inner class is a non-static
nested class. It has access to all of the variables and methods of its outer class and may
refer to them directly in the same way that other non-static members of the outer class do.
Thus, an inner class is fully within the scope of its enclosing class. The following
program illustrates how to define and use an inner class. The class named Outer has one
instance variable named outer_x, one instance method named test(), and defines one inner
class called Inner.
// Demonstrate an inner class.
class Outer {
int outer_x = 100;
void test() {
Inner inner = new Inner();
inner.display();
}
// this is an inner class
class Inner {
void display() {

16
System.out.println("display: outer_x = " + outer_x);
}
}
}
class InnerClassDemo {
public static void main(String args[]) {
Outer outer = new Outer();
outer.test();
}
}
Output from this application is shown here:
display: outer_x = 100
In the program, an inner class named Inner is defined within the scope of class Outer.
Therefore, any code in class Inner can directly access the variable outer_x. An instance
method named display( ) is defined inside Inner. This method displays outer_x on the
standard output stream. The main( ) method of InnerClassDemo creates an instance of
class Outer and invokes its test( ) method. That method creates an instance of class Inner
and the display( ) method is called. It is important to realize that class Inner is known
only within the scope of class Outer. The Java compiler generates an error message if any
code outside of class Outer attempts to instantiate class Inner. Generalizing, a nested class
is no different than any other program element: it is known only within its enclosing
scope. As explained, an inner class has access to all of the members of its enclosing class,
but the reverse is not true. Members of the inner class are known only within the scope
of the inner class and may not be used by the outer class. For example,
// This program will not compile.
class Outer {
int outer_x = 100;
void test() {
Inner inner = new Inner();
inner.display();
}
// this is an inner class
class Inner {
int y = 10; // y is local to Inner
void display() {
System.out.println("display: outer_x = " + outer_x);
}
}
void showy() {
System.out.println(y); // error, y not known here!
}
}
class InnerClassDemo {
public static void main(String args[]) {
Outer outer = new Outer();
outer.test();

17
outer.showy();
}
}
Here, y is declared as an instance variable of Inner. Thus it is not known outside of
that class and it cannot be used by showy( ).
/*In object-oriented programming, downcasting or type refinement is the act of casting a
reference of a base class to one of its derived classes. In other words, when a variable of
the base class (parent class) has a value of the derived class (child class), downcasting is
possible.*/
/*In object-oriented programming, upcasting is the act where parent variable is currently
holding by Child instance. In other words, when a variable of the derived class (child
class) has a value of the base class (parent class), upcasting is possible.*/
class Parent
{
void show1()
{
System.out.println("Hello - show1");
}
void show2()
{
System.out.println("Hello - show2");
}
void show3(){}
void show4(){}
}
class Child extends Parent
{
void show3()
{
System.out.println("Hello - show3");
}
void show4()
{
System.out.println("Hello - show4");
}
}
class TypeCasting
{
public static void main(String args[])
{
Parent p1=new Child(); //Down-Casting
p1.show1();
p1.show2();

18
p1.show3();
p1.show4();
System.out.println();
Child c1=(Child)p1; //Up-casting
c1.show1();
c1.show2();
c1.show3();
c1.show4();
System.out.println();
((Child)p1).show1(); //Up-casting
((Child)p1).show2();
((Child)p1).show3();
((Child)p1).show4();
}
}

Das könnte Ihnen auch gefallen