The Constitution Review Committee (CRC) has released an updated schedule for ...nservice241
People & Earth's Ecosystem -Lesson 2: People & Populationmarvinnbustamante1
Ad
Programming in Java Unit 1 lesson Notes for Java for Elearners
1. 24
UNIT II
Objective: To equip the student with programming knowledge in Inheritance,
Package, Interface and Exception handling
INHERITANCE
When one class acquires the properties of another class it is known as inheritance.
A class that is inherited is called a super class or base class.
The class that does the inheriting is called a subclass or derived class.
Advantage of inheritance is that it allows reusability of coding.
TYPES OF INHERITANCE
Inheritance may take different forms. They are
Single inheritance (one super class, one sub class)
Multilevel inheritance (derived from a derived class)
Multiple Inheritance
Single inheritance
Single class is one in which there exists single base class and
single derived class.
Multi level inheritance
Multi level inheritance is one which there exist single base class, single derived class
and n number of intermediate base classes.
An intermediate base class is one, in one contest it acts as base class and in
another context it acts as derived class.
Multiple Inheritance
Multiple inheritances are one supported by JAVA through classes but it is supported
by JAVA through the concept of interfaces.
Defining a subclass
A subclass is defined as follows:
class subclassname extends superclassname
2. CDOE-ODL BSc(CS) SEMESTER IV Unit II
25
{
variables declaration;
methods declaration;
}
The keyword extends signifies that the properties of the super classname are
extended to the subclassname.
SUBCLASS CONSTRUCTOR
A subclass constructor is used to construct the instance variables of both the
subclass and the super class.
The sub class constructor uses the keyword super to invoke the constructor
method of the super class.
The keyword super is used in following conditions. Super may only be used
within a subclass constructor method.
The call to super class constructor must appear as the first statement within the
sub class constructor.
The parameter in the super call must match the order and type of the instance
variable declared in the program.
MEMBER ACCESS RULES
The modifiers are also known as access modifiers.
Java provides three types of visibility modifiers: public, private and protected.
Public Access:
To declare the variable or method as public, it is visible to the entire class in which it
is defined.
Example:
public int number;
Friendly Access:
When no access modifier is specified, the number defaults to a limited version of
3. CDOE-ODL BSc(CS) SEMESTER IV Unit II
26
makes fields visible in all classes.
While friendly access makes fields visible only in the same package, but not in other
package.
Protected Access:
The protected modifier makes the fields visible not only to all classes and
subclasses in the same package but also to subclasses in other packages.
Non-
Private Access:
Private fields are accessible only with their own class.
They cannot be inherited by subclasses and therefore not accessible in subclasses.
A method declared as private behaves like a method declared as final.
Private protected Access:
A field can be declared with two keywords private and protected together like:
private protected int codeNumber;
Use public if the field is to be visible everywhere.
Use protected if the field is to be visible everywhere in the current package and also
subclasses in other packages.
current package only.
METHOD OVERLOADING
Method overloading is creating methods that have same name, but different
parameter lists and different definitions. Method overloading is used when objects
are required to perform similar tasks but using different input parameters.
4. CDOE-ODL BSc(CS) SEMESTER IV Unit II
27
When a method is called, java matches up the method name first and then the
number and type of parameters to decide which one of the definitions to execute.
This process is known as polymorphism.
Ex:
class room {
float l,b;
room(float x, float y) {
l=x;
b=y; }
room(float x) {
l = b = x; }
int area() {
return(l * b); }
}
METHOD OVERRIDING
A method defined in a super class is inherited by its sub class and is used by the
objects created by the sub class.
There may be occasions when we want an object to respond to the same method
is called.
This is possible by defining a method in the sub class that has the same name,
same arguments and same return type as a method in the super class.
When the methods are called, the method defined in the sub class is invoked and
executed instead of the one in the super class. This is known as overriding.
Example
class Super {
int x;
void display () {
} }
class overridetest {
public static void main (String args[]) {
Sub S1=new Sub (100, 200);
S1.display (); } }
Super (int x) {
this.x=x;
}
void display () {
} }
class Sub extends Super {
int y;
Sub (int x, int y) {
super (x);
this.y=y; } }
5. CDOE-ODL BSc(CS) SEMESTER IV Unit II
28
ABSTRACT METHODS AND CLASSES
In JAVA we have two types of classes. Concrete classes and abstract classes.
They are
A concrete class is one which contains fully defined methods. Defined methods
are also known as implemented or concrete methods. With respect to concrete
class, we can create an object of that class directly.
An abstract class is one which contains some defined methods and some
undefined methods. Undefined methods are also known as unimplemented or
abstract methods. Abstract method is one which does not contain any definition.
To make the method as abstract we have to use a keyword called abstract before
the function declaration.
ABSTRACT METHODS
When a method is defined as final than that method is not re-defined in a
subclass.
Java allows a method to be re-defined in a sub class and those methods are
called abstract methods.
When a class contains one or more abstract methods, then it should be declared
as abstract class.
When a class is defined as abstract class, it must satisfy following conditions.
o
Op s = new Op( ) - is illegal because Op is an abstract class.
o The abstract methods of an abstract class must be defined in its sub class.
o
Final allows the methods not redefine in the subclass.
Abstract method must always be redefined in a subclass, thus making overriding
compulsory.
This is done using the modifier keyword abstract in the method definition.
6. CDOE-ODL BSc(CS) SEMESTER IV Unit II
29
FINAL VARIABLES AND METHODS
It prevents the subclasses form overriding the member of the superclass.
Final variables and methods are declared as final using the keyword final as a
modifier.
Example: size =100
final int SIZE = 100;
Making a method final ensures that the functionality defined in that method
will never be altered in any way.
The value of a final variable can never be changed.
FINAL CLASSES
A class that cannot be sub-classed is called a final class.
It prevents a class being further sub-classed for security reasons.
Any attempt to inherit these classes will cause an error.
final class Aclass
{
}
Final class Bclass extend someclass
{
}
FINALIZER METHODS
declared. This process is called initialization.
frees up the memory resources used by the objects. This process is known as
finalization.
It acts like a destructor.
The method can be added to any class.
The finalize( ) method has this general form: 99
7. CDOE-ODL BSc(CS) SEMESTER IV Unit II
30
protected void finalize( )
{
// finalization code here }
Here, the keyword protected is a specifier that prevents access to finalize( ) by
code defined outside its class.
PACKAGES
A package is a collection of classes, interfaces and sub-packages.
A sub-package in turns divides into classes, interfaces, sub-sub-packages, etc.
Learning about JAVA is nothing but learning about various packages.
By default one predefined package is imported for each and every JAVA program
and whose name is java.lang.*.
Whenever we develop any java program, it may contain many number of user
defined classes and user defined interfaces.
If we are not using any package name to place user defined classes and
interfaces, JVM will assume its own package called NONAME package.
In java we have two types of packages they are
predefined or built-in or core packages and user or secondary or custom defined
packages.
BENEFITS:
The classes contained in the packages of other programs can be easily reused.
In packages, classes can be unique compared with classes in other packages.
That is two classes in two different packages can have the same name.
They may be referred by their fully qualified name, comprising the package name
and the class name.
Packages provide a way to "hide" classes thus preventing other programs or
packages from accessing classes that are meant for internal use only.
Packages also provide a way for separating "design" form "coding".
8. CDOE-ODL BSc(CS) SEMESTER IV Unit II
31
USING PACKAGES
Packages are organized in a hierarchical structure.
o The package named java contains the package awt, which in turns contain
various classes required for implementing graphical user interface. Best
and easiest one to access the class
o Used only once, not possible to access other classes of the package.
There are two ways of accessing the classes stored in a package
1. Using the fully qualified class name. (Using the package name containing the
class and then appending the class name by using the dot operator.)
E.g. java.awt.Color
2. Using the import statement, appear at the top of the file. Imported package class
can be accessed anywhere in the program
Syntax:
import packagename.classname;
Or
import packagename.*
These are known as import statements and must appear at the top of the file, before
any class declarations, import is a keyword.
The first statement allows the specified class in the specified package to be
imported. For example, the statement
import java.awt.Color;
imports the class Color and therefore the class name can now be directly used in
the program.
The second statement imports every class contained in the specified package.
For example, the statement
import java.awt.*;
will bring all classes of java.awt package.
9. CDOE-ODL BSc(CS) SEMESTER IV Unit II
32
INTERFACES
Interfaces are basically used to develop user defined data types.
With respect to interfaces we can achieve the concept of multiple inheritances.
With interfaces we can achieve the concept of polymorphism, dynamic binding
and hence we can improve the performance of a JAVA program in turns of
memory space and execution time.
An interface is a construct which contains the collection of purely undefined
methods or an interface is a collection of purely abstract methods.
interface <InterfaceName>
{
variables declaration;
methods declaration;
}
Here, interface is the keyword.
Interface name represent a JAVA valid variable name.
Variables are declared as follows:
static final type VariableName = Value;
All variables are declared as constants. Methods declaration will contain only a list of
methods without any body statements.
return-type methodName1 (parameter_list);
EXTENDING INTERFACES
Interface can also be extended.
An interface can be sub-interfaced from other interfaces.
The new interface will inherit all the member of the super-interface.
Interface can be extended using the keyword extends.
interface name2 extends name1
{
Body of name2
}
10. CDOE-ODL BSc(CS) SEMESTER IV Unit II
33
IMPLEMENTING INTERFACES
Implement the interface using implements keyword.
General form1
class classname implements
interfacename
{
body of classname
}
General form2
class classname extends supperclass
implements
{
body of classname
}
EXCEPTION HANDLING
Exceptions: An exception is a condition that is caused by a run-time error in the
program.
A java exception is an object that descirbes an error condition occurred in a piece
of code. Exceptions can be generated by the Java run-time system or they can
be manually generated by code.
Exceptions thrown by a Java relate to fundamental errors that violate the rules of
the Java language or the constraints of the Java execution environment.
Manually generated exceptions are typically used to report some error condition
to the caller of a method.
Java exception handling is managed via try, catch, throw, throw and finally.
Exception types
All exceptions are subclasses of Throwable class. There are two subclasses that
partition exception into two distinct branches, Exception and Error.
Exception this class is used for exceptional conditions that user program should
catch. The class defined for custom exceptions are subclass to this class. A
special subclass called RuntimeException, Exception of this class is
automatically defined for a program.
Error This class defines exceptions that are not expected under normal
circumstances. Exceptions of this type are used by the Java run-time system to
indicate errors having to be deal by the run-time environment itself.