Java 1-4 Units
Java 1-4 Units
JAVA
Genesis of Java
To know about genesis of java, first we need to know about C and C++.
Evolution of C++: C++ is a response to the above said need. Although C is one of the world's
great programming languages, there is a limit to its ability to handle complexity. Once a
program exceeds somewhere between 25,000 and 100,000 lines of code, it becomes so complex
that it is difficult to grasp as a totality. C++ allows this barrier to be broken, and helps the
programmer comprehend and manage larger programs. By the end of the 1980s and the early
1990s, object-oriented programming using C++ took hold. Object oriented programming has
given a new dimension to the programming world the era is continuing. With the help of OOPS
concept, software design has been changed. The main object oriented principles are: data
abstraction, inheritance.
Creation of JAVA:
Inspite of having more features, C and C++ are unable to provide portability in a greater extent.
This is where Java is different in its own way because of “platform independency”.
Java is purely object oriented language conceived by James Goslings and his team
members at Sun Microsystems in 1991. The initial name of the language was ‚oak‛ and after
that it was renamed as Java. The complete version of the language was released in 1995. Java
has got much popularity because of its well known concept ‚platform independency‛.
Platform Independency: Literally speaking, the concept of platform independency makes java
as architecture neutral language. i.e., consider the other languages C & C++, they are designed
to be compiled for any specific application. To compile any application related to C & C++, we
need a full compiler that has the compatibility to the working CPU otherwise it becomes tough
to manage applications. To provide better portability, Sun Microsystems concentrated on a new
language and the result was Java. It can produce code that would run on a variety of CPUs
under different environments. We can say that java has given a new dimension to the
programming approach in terms of platform independency. Once java code is produced it can
be run anywhere on any environment. Moreover, as the java code runs on any platform, it can
be adapted to internet too because internet programming does require the same kind of
approach. In fact, Java is no longer a language that is designed for internet programming.
Instead, the primary motivation was the need for a platform-independent (that is, architecture-
neutral).
‚Platform independency is achieved by java through its JVM (Java Virtual Machine)‛
Unlike other languages like C & C++, java compiler generates architecture-independent byte
codes. A Java Virtual Machine can execute the byte codes only. Symbolically:
Another programming advantage is that Java has syntax similar to that of C++, making it easy
for C and C++ programmers to learn
JVM is a tool that provides platform independency to the language. The Java compiler is
machine dependent & JVM is machine dependent, it is the only byte codes that are machine
independent. The following diagram depicts the same.
Unix JVM
Macintosh
Java Compiler
Unix
Workstation Other O.S
Java Compiler JVM
Translating a Java program into byte code helps makes it much easier to run a program
in a wide variety of environments. The byte codes are the intermediate codes managed in a class
file. All the components of JVM provide flexibility to the user.
A Java virtual machine (JVM) is a virtual machine capable of executing Java byte code.
It is the code execution component of the Java software platform. A Java virtual machine is
software that is implemented on virtual and non-virtual hardware and on standard operating
systems. A JVM provides an environment in which Java byte code can be executed.
JVMs are available for many hardware and software platforms. The use of the same byte
code for all JVMs on all platforms allows Java to be described as a "write once, run anywhere"
programming language, as opposed to "write once, compile anywhere", which describes cross-
platform compiled languages.
Java byte code is an intermediate language which is typically compiled from Java, but it
can also be compiled from other programming languages.
Java’s security model has three components to look after: class loader, byte code verifier
and Security Manager. The Class Loader loads all the required class files in to the disk. The byte
code verifier ensures that the Java programs have been compiled correctly, that they will obey
the Virtual Machine’s access restrictions, and the byte codes will not access ‘private data’. The
Security Manager implements a security policy for the VM. The security policy determines
which activities the VM is allowed to perform, and under what circumstances.
The JVM fetches classes from a disk or from the network, and then verifies that the byte codes
are safe to be executed. From the diagram let us see what these components of a JVM do. In
addition the byte code verifier checks for the following:
- Access restriction violation.
- Object mismatching.
- Operands stack over or under flow.
- Incorrect byte code parameters.
- Illegal data conversion.
Java Byte Codes: Java byte code is an intermediate language which is typically compiled
from Java, but it can also be compiled from other programming languages. Most programming
languages compile source code directly into machine code, suitable for execution on particular
microprocessor architecture. The difference with Java is that it uses byte code - a special type of
machine code.
Java byte code is the form of instructions that the Java virtual machine executes. Each
byte code opcode is one byte in length. Not all of the possible 256 opcodes are used. 51
are reserved for future use.
When a JVM loads a class file, it gets one stream of byte codes for each method in
the class. The byte codes streams are stored in the method area of the JVM. The byte
codes for a method are executed when that method is invoked during the course of
running the program. They can be executed by interpretation, just-in-time compiling, or
any other technique that was chosen by the designer of a particular JVM.
JDK is a Java’s Development Tool. It contains a set of command line tools with which Java
programs can be compiled, debugged and interpreted. Some of the important tools are :
Java Compiler (javac)
Java Runtime Interpreter (java)
Applet Viewer (appletviewer)
Java Debugger (jdb)
Java Achiever (jar)
Javap (java disassembler)
Javah (Java Header)
API Source Code
The standard Edition is for implementing general & standard applications i.e., core and desktop
applications where as the Enterprise Edition provides techniques to develop complex
enterprise/server applications. There is another edition supported by Java called ‚J2ME‛ which
concentrates more on mobile wireless applications using Java. For both the versions of Java, Sun
Microsystems has given free downloads at net. The information and new updates along with
software, you can obtain from the site java.sun.com.
Note: The other sites are javasoft.com, orielly.com
The java software was released by Sun Microsystems and its name is JDK (Java Development
Kit). The early version was JDK 1.0. After that JDK 1.1, JDK 1.2 was released. At present the
working version is JDK 1.4.2. Beta version for J2SE 5.0 is already released. The JDK1.2 is a major
upgrade of the core and standard extension APIs of Java Development Kit. It includes version
1.1 of the Java Foundation Classes (JFC). ‚JFC is collection of APIs for building the GUI-related
components of Java Applets and applications‛.
The second phase is compilation stage and javac is the command line tool to compile a java
program. The compiler generates class file (.class file) and a class file is collection of byte codes
which a java interpreter can understand in execution stage.
The third phase is known as loading stage. Before the program’s execution, the .class file
should be placed in the memory. A class loader searches for a .class file in the directory and
loads it in the memory.
The fourth phase is the verification phase. Before the program is executed, byte code verifier
validates the byte codes for not violating the Java security restrictions which is of great concern
in internet.
The fifth phase is last phase, which is known to be execution stage. At this stage the java
program gets executed.
Simple: Java language is simple to use and easy to learn. It manages to handle all of its concepts
in quite flexible manner. If the programmer is already aware of object oriented concepts, it
becomes even easier. Moreover, it extracts all most all the features of C/C++. Java was designed
to be easy for the professional programmer to learn and use effectively.
Secure: All the Java that provides the user is nothing but secured programming techniques.
Java implements a separate Security Manager so that the user can be benefited in implementing
the objects with ease of use. Java is intended to be used in networked/distributed environments.
Toward that end, a lot of emphasis has been placed on security. Java enables the construction of
virus-free, tamper-free systems
Strongly typed: Often, saying Java is a strongly typed language is absolute because it is very
much particular about the type of the data. The user needs to be careful while dealing with data
types.
Portability: As Java generates a byte codes (class file) as intermediate files, it can be ported to
any platform without any problem. This itself is one of the major advantages of Java.
Architecture neutral: A central issue for the Java designers was that of code longevity and
portability. One of the main problems of a programmer is that no guarantee exists that if you
write a program today, it will run tomorrow – even on the same machine. As Java runs on JVM,
this problem may not arise. Hence you can assume that Java is architecture – neutral language.
The main goal was "write once; run anywhere, anytime, forever." To a great extent, this goal
was accomplished.
Object oriented: Object oriented programming was well proven technique with all of its
concepts like polymorphism, inheritance. In future, it may get even more potentiality in
software development. Hence implementing such concept will be an added advantage of Java.
Moreover, the learner may not be in the illusion that he is learning a new language. The object
model in Java is simple and easy to extend, while simple types, such as integers, are kept as
high-performance non --objects.
Dynamic: Dynamic nature of Java gives more comfortness to the designer because dynamic
declaration & redeclaration of data members becomes easy at runtime. This makes it possible to
dynamically link the code in a safe manner.
Distributed: Java is designed for distributed environments like Internet, because it handles
TCP/IP protocols. With this nature Java objects are distributed over the network and get
executed remotely on demand.
Multithreaded: Java has another advantage of allowing the user to develop interactive,
networked programs. To achieve this, Java supports multithreading this allows you to run
many tasks simultaneously. Java provides built-in support for multithreading so that the user
can design such application in a most sophisticated way.
Interpreted & High Performance: Java enables the creation of cross-platform programs by
compiling into an intermediate representation called Java bytecode. This code can be
interpreted on any system that provides a 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. Java run-time systems that provide this feature
lose none of the benefits of the platform-independent code.
A data type tells about the type of the data being assigned to an identifier or data name. Java
supports the following list of data types.
Note: Java doesn’t support keyword ‚unsigned‛. So data types of unsigned type cannot be
defined.
JAVA OPERATORS
Similar to all the other languages, Java supports all the operators like arithmetic operators,
logical operators, relational operators and bit-wise operators.
Addition +
Subtraction -
Multiplication *
Division /
Modulus %
Increment ++
Decrement --
Addition Assignment +=
Subtraction Assignment -=
Multiplication Assignment *=
Division Assignment /=
Logical Operators: To evaluate expressions that result in either ‘true’ or ‘false’ value.
Relational Operators: These operators are used to test for equality of expressions. They result
in either ‘true’ or ‘false’ value.
Java Keywords: A keyword is a word that has a special meaning in the JAVA compiler. There
are 48 keywords in JAVA.
Generally, the statements in a program get executed in the order in which they are written. This
is referred as Sequential Execution. If the programmer wants to execute some statements even
before other statements by surpassing the order, he must transfer the control of the program
temporarily. This can be achieved with control structures like if, for and switch etc.,
The ‘if’ structure is called as a single selection structure because it selects or ignores a single
action. The if ..else structure is said to be double selection structure because it selects either of
two different actions.
Switch Structure
If is for single selection and if.. else is for double selection. When there is a situation where
multiple conditions are to be evaluated then it is always better to use switch structure. The
switch structure contains a set of case labels, and an optional default case. Each case label is
terminated by a statement break.
switch(condition/expression)
{
case constant:
statements;
break;
case constant:
statements;
break;
<<<<<..
default:
statements;
break;
}
Here case, break, default are the keywords.
While Structure:
While & For structures are said to be repetitive control structures or looping structures as the
programmer can repeat the execution of the same statements as many times as required. The
process of executing a block of statements terminates when the condition becomes false.
Syntax: While(condition)
{
Set of statements’
}
For Structure:
The ‘for’ structure is also a looping structure that performs a statement / a block statements for a
specified no. of times. In other words, for control structure may be used if the no. of iterations is
definite
Syntax:
for(initialization; condition; incrementation/decrementation)
{
Statements
}
In JDK1.5, a new version of for control structure was introduced. The syntax follows:
OOPS Features:
1. Classes and objects
2. Data abstraction
3. Data encapsulation
4. Message Passing
5. Polymorphism
6. Inheritance
7. Extensibility
Class
A class is a blue print for generating various objects (or) a class is a blue print that defines the
variables and methods common to all objects of a certain kind (or) a class is a prototype based
on which objects can be derived (or) a class is a collection of data and it’s corresponding
methods. Or a class is a description of several objects.
NAME
- DATA
# DATA
+ DATA
- METHOD
#METHOD
+METHOD
Object
An object is an instance of a class. In other words an object is a physical construct that occupies
certain amount of space in memory.
As a class is a logical construct, it doesn’t occupy any memory where as an object is a
physical construct and it occupies certain space.
The fundamental concept for OOP is an ‘object ‘, which is an entity that has existence.
An object fundamentally consists of three characteristics:
A state
A behavior
An identity
Data abstraction: Abstraction is the process of exhibiting only the essential characteristics of an
object depending on programmers view. Abstraction is of two types:
Data abstraction
Functional Abstraction
Ex :
Data Abstraction - Empno, Ename, Desg, salary
Functional Abstraction - getDetails( ), dispDetails( )
Polymorphism: It is the ability to provide multiple definitions to the same method signature. It
allows providing one interface multiple methods.
Inheritance: It is the ability to extract the features of one class to another. It is one of the striking
features of inheritance. Java supports inheritance extensively as the main objective of
inheritance is code reusability.
Advantages of OOPs:
Modularity: All classes and objects can be treated as separate modules. This makes the
designing simpler.
Ease of Maintenance: Code is easier to maintain. The concept of encapsulation localizes
the errors. I.e., debugging is made easy.
Reusability and Extensibility: Through the concept of inheritance, we can easily extend
existing classes. We can alter the behavior and also add new features. Code reusability
is the great advantage.
Powerful modeling paradigm: The system based on OOP is close to real world and
hence simple to understand.
Import section
Package declaration section // if needed
Interface declaration & definition section // if needed
Public class class-name
{
static variable declaration; // if needed
public static void main( String s [ ] )
{
body of main()
}
other static function definitions //if needed
} //end of main class
other class definitions. // if needed
Declaration of Objects
As Java is an object oriented language, any no. of classes can be defined in a program. If a class
is defined, user has to create an object for that class to make use of the data. In fact it is a two
step process.
First you must declare a variable of the class type. This variable doesn’t define an object.
Instead, it is simply an object reference.
Second, we create a physical copy for the class and assign the address to the reference. To do
this, use ‚new‛ keyword. The new keyword dynamically allocates memory for an object and
returns the address.
Ex :
Box B; //creating a reference null
B = new Box( ); B
B
Width
Height
Example:
depth
Public class demo
{
public static void main(String s[ ])
{
test t = new test( ); // instance for class test is created
t . display( );
}
} // end of main class
class test
{
int a ;
public void display( )
{
a = 101;
System.out.println( ‚the value of a is <..‛+a);
}
} // end of other class.
Note:
1) If a program execution is over, the corresponding objects created will automatically be
destroyed by the built-in garbage collector of JVM which will be invoked once the objects go
beyond the scope of the programmer.
2) If we do not initialize the instance variables then they automatically assigned certain values.
A static variable is a variable that can be shared by all the objects of same class. A static variable
once initialized cannot be redeclared. Static keyword must be specified before the variable
name. It can be accessed by the class name. The user needs not to create an object for the class in
which it is defined.
Similarly a static method is one whose implementation is exactly the same for all the objects of
particular class. A static method will have access to static data only.
class test
{
public void display( )
{
System.out.println( ‚demo for static methods‛ );
}
} // end of other class.
Constructor
A constructor is a member function that initializes an object (or) a constructor is a member
function or method that gets invoked without making an explicit call to it (or) a constructor is a
method that gets called at the time of creation of an object for a class. It is the only method that
gets invoked first without the knowledge of the user.
Types of Constructors:
Default constructor
Parameterized constructor
Example:
class test
{
int a ;
public test( ) // constructor definition.
{
a = 101;
}
public void display( )
{
System.out.println( ‚The value of a is <..‛+a);
}
} // end of other class.
Parameterized Constructor:
The compiler creates a default constructor if we do not specify any constructor. A constructor
can also have certain parameters or arguments; such a constructor is called as parameterized
constructor.
Ex :
public class demo
{
public static void main(String s[ ])
{
test t = new test(12,11.45f ); // instance for class test is created
t . display( );
}
} // end of main class
class test
{
int x ; float y;
public test( int a, float b) // constructor definition.
{
x = a; y = b;
}
public void display( )
{
System.out.println( ‚The values of x & y are <..‛ + x +‛ ‚+ y );
}
} // end of other class.
‘this’ keyword:
‚this‛ is a keyword that refers to the current object in use. It is used in the method of a class. In
other words, this keyword refers to the object on which the method was invoked.
Ex1:
class test
{
int a, float b, char c;
public test ( int a, float f, char c )
{
this. a = a;
this . b = b;
this . c = c;
}
}
Ex2:
class Complex
{
int r,i;
public Complex(int r, int i)
{
this.r = r;
this.i = i;
}
public void show()
{
System.out.println(r+" "+i+"i");
}
public Complex add(Complex x)
{
r += x.r;
i += x.i;
return this; // it returns current object i.e., object ‘a’.
}
}
a.show();
b.show();
Complex c = a.add(b);
c.show();
}
finalize( )
In fact in Java, objects once created can be destroyed automatically. Java provides built-in
garbage collector to gather all the unused objects for destruction. So, the programmer needs not
to implement any destructor method explicitly. However, sometimes it is necessary to perform
certain actions before destroying the object. In such cases implementation of such actions is
done in a method called finalize( ).
POLYMORPHISM:
All the methods are differentiated by means of: types of arguments & number of arguments.
For ex: No. of arguments:
Show()
Show(int)
Show(int,int);
Types of arguments:
Show(int);
Show(double)
Show(long)
Show(String)
Method overloading is commonly used to create several methods with unique name to
perform similar kind of tasks, but with different data. i.e., it is possible to define two or more
methods within the same class that share the same name, as long as their parameters
declarations are different. If this is the case, the whole process is said to be method overloading.
It is also known as compile time polymorphism or early binding or compile time binding. Here
binding means associating method call with the method definition.
Ex:
class demo
{
int a , b;
public void get_data( )
{
a = 10;
b = 20;
}
public void get_data( int a )
{
this . a = a;
b = 30;
}
public void get_data( int a , int b)
{
this . a = a;
this . b = b;
}
public void display( )
{
System.out.println(‚the values are <<<.‛+a+‛ ‚+b);
}
}
public class test
{
public static void main( String s[ ] )
{
demo d = new demo( );
d.get_data( );
d. display( );
demo d = new demo( );
d.get_data(12 );
d. display( );
demo d = new demo( 44,55);
d.get_data( );
d. display( );
}
Constructor Overloading
An interesting feature of a constructor is that a class can have multiple constructors. This is
called as constructor overloading. All the constructors have the same name as the
corresponding class, and they differ only in terms of their signature (i.e., in terms of no. of
arguments or data types of their arguments or both). However, as a constructor is also a
method of a class, it can also be overloaded.
Ex:
class demo
{
int a , b;
public demo( )
{
a = 10; b = 20;
System . out . println(‚the values are <<<.‛+a+‛ ‚+b);
}
INHERITANCE
One of the most striking features of an Object Oriented language is nothing but inheritance.
Inheritance is a process of achieving code reusability. With inheritance code duplication is
avoided by reusing the code (attributes and methods) of one class in another class. In other
words it is a process of extraction of the features of one class into another.
A class that inherits another is said to be a subclass/child class and a class that is being inherited
by other is referred as super class/ parent class. To achieve this, use ‚extends‛ keyword while
defining the subclass.
Example: Person → Student → Engineer → Computer Scientist
There are several types of inheritances in OOPs and the list follows:
Single Inheritance
Multiple Inheritance
Multilevel Inheritance
Hierarchical Inheritance
Hybrid Inheritance
Single Inheritance: In Single Inheritance, one class inherits the features of only one class. i.e.,
there exists only one super class & one sub class.
Super Class: a class that is being inherited by some other class is a super class
Subclass: a class that inherits other classes is the sub class.
In fact, if class B inherits a class called A, all the methods of A can be invoked through the object
of B as if they are defined in class B. The user need not to create an object for the super class to
access it’s methods as you have an object of it’s sub class. Hence we say that all the attributes
and methods of public type in super class become public in corresponding sub classes. The
following example illustrates the same.
Ex: class A
{
public void show1( )
{
System.out.println( ‚super class method 1‛);
}
public void show2( )
{
System.out.println(‚ super class method 2 ‚);
}
}
class B extends A
{
public void show3( )
{
System.out.println( ‚sub class method 1 ‚);
}
public void show4( )
{
System.out.println( ‚sub class method 2 ‚);
}
}
Multilevel Inheritance: In this inheritance, there will be multiple super classes and sub classes.
For example, class A is inherited by class B and class B is inherited by class C and class C is
inherited by another class called D and the process will go on. This is referred as multilevel
inheritance.
A
Super class/ base class/parent class
B
Intermediate super class
Hierarchical Inheritance: This inheritance follows a tree structure. Multiple classes may inherit
one class. Hence this category is referred as hierarchical inheritance. i.e., one super class and
multiple subclasses.
A
B C
Example:
Student Account
Cricketer
Batsman Bowler
Method Overriding
In a class hierarchy, when a method in sub class has the same name and type signature as a
method in its super class, then the method in the sub class is said to override the method in the
super class. The whole process is said to be method overriding. Moreover, When a method in
the sub class is called then always the method defined in the sub class only gets invoked.
An overriding method must not be less accessible than the method it overrides.
An overriding method must not throw any checked exceptions that are not declared
by the overriding method.
Ex :
class A
{
public void show( )
{
System.out.println( ‚ super class method ‚);
}
}
class B extends A
{
public void show( )
{
System.out.println (‚ sub class method info ‛);
}
}
public class demo
{
public static void main(String s [ ] )
{
B b = new B ( );
b.show ( );
}
}
Super Keyword
Super is a Java keyword that used to reference no-static methods or variables of that parent
class that may be hidden by the current class. There are two different situations where ‚super‛
keyword comes in to picture.
In fact, if we define a parameterized constructor in both super and sub classes then it becomes
difficult to send arguments to the super class constructor as we do not create an object to it. In
such cases, through the sub class constructor one can send/pass arguments to the corresponding
super class. To achieve this, we take the help of ‚super‛ keyword.
Ex :
class superclass
{
int a , b;
public superclass( int a, int b )
{
this. a = a; this. b = b;
}
public void show ( )
{
System.out.println( ‚ the values passed from ‚ + ‚ the sub class are <.‛ +a+ ‚ ‚ +b);
}
}
class subclass extends superclass
{
public subclass(int a, int b)
{
super ( a , b);
System.out.println(‚arguments are passed successfully‛);
}
}
public class superdemo
{
public static void main(String st[ ])
{
subclass s = new subclass(22 , 33);
s. show ( );
}
}
Note: While passing arguments from sub class to super class, the first statement must be the
super keyword otherwise the compilation error raises.
Abstract Classes
So far the classes you have created and practiced are called concrete classes for the reason that
we can create objects from the classes. But some classes do exist where you cannot create
objects from the objects. These classes are called abstract classes. In some other way we can say
that sometimes we need such a super class which doesn’t implement methods, instead, it
creates a generalized form for a method that will be shared by all of its subclasses. Now such
super class is referred as abstract class.
Literally, an abstract class is an incomplete class whose methods are defined in the
corresponding subclasses.
Any class that contains one or more methods must be declared as abstract.
‚abstract‛ is the keyword to be used while defining a class as abstract.
No object is created to an abstract class.
No abstract constructors & static methods of abstract type can be defined.
Along with abstract methods, complete methods can also be defined.
Ex :
abstract class Area
{
public void area ( ) ;
}
class Square extends Area
{
int a;
int result;
public void area ( )
{
result = a * a;
System.out.println ( ‚the area of a square is<<<‛+ result );
}
}
The other advantage of Method Overriding is nothing but Dynamic Method Dispatch. It is a
mechanism by which a call to an overridden method is resolved at runtime, rather than compile
time. The concept o dynamic method dispatch is vital because this is how Java implements or
achieves runtime polymorphism.
In Dynamic Method Dispatch, a general principle of holding or referring a subclass
object through the super class object reference variable is implemented.
For example, there is a super class A being inherited by two subclasses B & C and all the
three classes are implementing overridden methods. Now, Java determines which version of
those methods to be executed at run time. In some other way, ‚it is a type of the object being
referred to‛ that determines which version of an overridden method is executed.
Ex :
abstract class Super
{
abstract public void display( );
}
int a;
a = Integer . parseInt (s[0]);
if ( a == 1)
ss = new Subclass1(); // obtaining the reference of subclass 1
else
if ( a == 2)
ss = new Subclass2(); ; //obtaining the reference of subclass 2
ss . display ( ) ;
}
}
final keyword
Java has given a new way of approach to prevent method overriding and inheritance as well. In
certain situations, the user may not want to override a method. To achieve this, use final
keyword. Any method declared as final in a super class can not be overridden in the
corresponding sub class.
Interfaces
interface interface_name
{
return type methodname(arg.list);
return type methodname(arg.list);
--------
}
Ex:
interface interface1
{
public void show1( );
public void show2( );
}
class Myclass implements interface1
{
public void show1( )
{
System.out.println( ‚this is the first method implementation of interface ‚ );
}
All the fields (also known as variables) in a given interface are defined automatically as
static and final even if we do not specify.
All the methods in a given interface are automatically abstract & public even if we do
not specify.
No method must be defined.
A class may inherit any no. of interfaces.
All the methods in an interface must be declared as public while defining in the
corresponding subclasses.
We can create reference to an interface just like an abstract class.
One interface can extend another interface.
An interface can’t inherit a class.
Note: While inheriting an interface, a class must use ‚implements‛ keyword and while
inheriting an interface to another interface, use ‚extends‛ keyword.
Relationships:
HAS-A Relationship is given below: It represents a class that holds the object of another class.
i.e., a class HAS An object of some other class. In such situation the first class is the container
class. Suppose class A holds object of class B as a member then A is the container class.
Ex:
class B {
public void show()
{
System.out.println("Hello");
}
class A
{
B x;
public void display()
{
x = new B();
x.show();
System.out.println("Hai");
}
}
PACKAGES
Java packages can be stored in compressed files called JAR files, allowing classes to
download faster as a group rather than one at a time. Programmers also typically use packages
to organize classes belonging to the same category or providing similar functionality.
It helps Organize your classes into a folder structure and make it easy to locate and use
them. More importantly, It helps improve re-usability.
In general all the user defined java classes get stored in a default package. Packages &
interfaces are the basic elements for a Java program. All the predefined classes & interfaces of
Java are existed in terms of predefined packages. For example, java.lang, java.util, java.net,
java.awt etc., together the packages are said to be Java API (Application Programming
Interface).
A package is to be included in the user application so that the predefined classes can be
used. To achieve this, one can use a keyword called ‚import‛. Packages are of two types:
predefined & user defined. The following is the list of predefined packages:
java.lang- essential classes like thread, object and string
java.awt – graphical user interface components
java.io - input/output streams and files
java.net - networking related classes
java.applet – applet creation
java.util - utility classes like data and classes for data
structures
java.rmi - classes for remote method invocation
java.sql - classes for interacting with a database
For example, the statement import java.lang.*; includes all the predefined Java language
classes in the current application. However, java.lang is a package that is by default imported.
This statement must be the first statement to place the class in the specified package. A
hierarchy of packages can be defined as follows :
Here pkg2 is the sub package of pkg1 and pkg3 is the sub package of pkg2.
All the Java predefined packages are existed in the ‚CLASSPATH‛ set by the environmental
variable.
Creating packages: Packages are defined using the package statement as under:
package Mypkg;
public class MyClass
{
// body of the class;
}
6. Compile the file. This creates the class file in the sub-directory.
Classpath: The java compiler and the java interpreter, for locating packages, use the classpath
environment variable. To the existing value of the of this variable the path to the newly created
package should be added under.
set CLASSPATH=path1;path2
or
The classes and interfaces defined in a package can be made use of in any program file with the
import statement. Following are the two forms of the import statement:
import <packagename>.<classname>;
import pacakgename.*;
example:
package p;
public class Complex
{
int r,i;
public Complex(int r, int i)
{
this.r = r;
this.i = i;
}
public void show()
{
System.out.println(r+" "+i+"i");
}
public Complex add(Complex x)
{
r += x.r;
i += x.i;
return this;
}
}
Save the above program as ‘Complex.java’ in the current working directory. Compile it
as follows:
It creates a folder with the name ‘p’ in F:\jpro and places the Complex.class file in
‘F:\jpro\p’. Here ‘–d ‘ is a switch represents directory. And dot(.) represents the current
working directory.
After this, create another file with the name DemoComplex.java and edit the following
code in the file:
public class DemoComplex
{
public static void main(String args[])
{
p.Complex a = new p.Complex(3,4); // creating object for Complex
// Class in package p
p.Complex b = new p.Complex(2,3);
a.show();
b.show();
p.Complex c = a.add(b);
c.show();
}
}
( Or )
import p.Complex;
a.show();
b.show();
Complex c = a.add(b);
c.show();
}
}
Save and compile the above & we get the expected results.
Access to variables and methods is done through access modifiers in Java. Access modifiers
specify the levels of access between class members and outside world (i.e., objects of other
classes). Java provides support for four types access modifiers:
private.
public.
protected.
default (when no modifier is specified).
public: It has global visibility. It is assumed as most generous access modifier as it provides
global accessibility to the variables and methods irrespective of class.
Protected: It works sometimes as public and sometimes as private. i.e., in all the subclasses, the
methods and variables of a class work as public and in all the non-subclasses, they work as
private.
default: If we do not specify any modifier, Java considers the method or variable as default. All
the variables and method that are defined as default are public if the class that wants to have an
access to these variables & methods is existed in the same package where the original class is
existed. i.e., if a variable or method is not specified any access modifier, then only classes
(including subclasses) in the same package can have access.
Container Class: A class that holds an object of some other class is nothing but a container class.
A container holds one or more child components. A container has a layout that determines how
the child components are arranged within the container.
class B {
class A
{
B x;
public void display()
{
x = new B();
x.show();
System.out.println("Hai");
}
}
Inner Classes:
An inner class is a class that is defined inside another class. There are four reasons:
An object of an inner class can access the implementation of the object that created
it—including data that would otherwise be private.
Inner classes can be hidden from other classes in the same package.
Anonymous inner classes are handy when you want to define callbacks on the fly.
Inner classes are very convenient when you are writing event-driven programs
Ex:
class Outer
{
private int a;
public Outer()
{
a = 10;
}
Inner classes are a major addition to the language. Inner classes are anything but
simple. The syntax is complex. Inner classes are translated into regular class files with $
(dollar signs) delimiting outer and inner class names and the virtual machine does not
have any special knowledge about them.
Sometimes inner classes are used only once in a method, in such cases we define
an inner class locally. Such classes are referred to as local inner classes.
Local classes are never declared with an access specifier (that is, public or private). Their
scope is always restricted to the block in which they are declared.
Local classes have a great advantage—they are completely hidden from the outside world.
Local classes have another advantage over other inner classes. Not only can they access
the fields of their outer classes, they can even access local variables! However, those
local variables must be declared final.
When using local inner classes, you can often go a step further. If you want to make
only a single object of this class, you don't even need to give the class a name. Such a
class is called anonymous inner class.
Local Class:
A local class is declared locally within a block of Java code, rather than as a member of a
class. Typically, a local class is defined within a method, but it can also be defined
within a static initializer or instance initializer of a class. Because all blocks of Java code
appear within class definitions, all local classes are nested within containing classes. For
this reason, local classes share many of the features of member classes.
The defining characteristic of a local class is that it is local to a block of code. Like a local
variable, a local class is valid only within the scope defined by its enclosing block.
Features of Local Classes: Local classes have the following interesting features:
Like member classes, local classes are associated with a containing instance, and
can access any members, including private members, of the containing class.
In addition to accessing fields defined by the containing class, local classes can
access any local variables, method parameters, or exception parameters that are
in the scope of the local method definition and declared final.
Restrictions on Local Classes: Local classes are subject to the following restrictions:
A local class is visible only within the block that defines it; it can never be used
outside that block.
Local classes cannot be declared public, protected, private, or static. These modifiers
are for members of classes; they are not allowed with local variable declarations
or local class declarations.
Like member classes, and for the same reasons, local classes cannot contain static
fields, methods, or classes. The only exception is for constants that are declared
both static and final.
Interfaces cannot be defined locally.
A local class, like a member class, cannot have the same name as any of its
enclosing classes.
OBJECT CLONING:
When you make a copy of a variable, the original and the copy are references to the
same object. This means a change to either variable also affects the other.