0% found this document useful (0 votes)
2 views20 pages

Bca 2nd Java Notes - Ch2

The document provides an overview of inheritance in Java, detailing its types such as single, multiple, hierarchical, and multilevel inheritance. It explains the concept of subclasses, method overriding, and the use of the final keyword to restrict modifications to classes, methods, and variables. Additionally, it covers abstract classes, visibility control through access modifiers, and the organization of classes into packages for better management and reusability.

Uploaded by

sowmyarani912
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views20 pages

Bca 2nd Java Notes - Ch2

The document provides an overview of inheritance in Java, detailing its types such as single, multiple, hierarchical, and multilevel inheritance. It explains the concept of subclasses, method overriding, and the use of the final keyword to restrict modifications to classes, methods, and variables. Additionally, it covers abstract classes, visibility control through access modifiers, and the organization of classes into packages for better management and reusability.

Uploaded by

sowmyarani912
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

OBJECT ORIENTED PROGRAMMING WITH JAVA

UNIT 2: INHERITANCE

Inheritance: Extending a class


Reusability is another concept of OOP. The mechanism of deriving a new class from an old one is called
inheritance. The old class is called the base class or super class or parent class and the new one is called
sub class or derived class or child class.

The inheritance allows subclasses to inherit all the variables and methods of their parent classes. Inheritance
may take different forms:
 Single inheritance (only one super class)
 Multiple inheritance (several super classes)
 Hierarchical inheritance (one super class, many subclasses)
 Multilevel inheritance (Derived from a derived class)
Java does not directly implement multiple inheritance. However, this concept is implemented using a
secondary inheritance path in the form of interfaces.

A A

B B C D
a. Single inheritance b. Hierarchical inheritance

A B
A

B
C

C
[Link] inheritance d. Multiple inheritance
fig : Forms of inheritance

1 Prepared By : Sowmya Rani G S, Lecturer, Govt Science College, Chitradurga


OBJECT ORIENTED PROGRAMMING WITH JAVA

Defining a Subclass
A subclass is defined as follows:
class subclassname extends superclassname
{
Variables declaration;
Method declaration;
}
The keyword extends signifies that the properties of the superclassname are extended to the subclassname.
The subclass will now contain its own variables and methods as well those of the superclass.

Program to illustrate the single inheritance

class Room
{
int length;
int width;
Room( int x, int y)
{
length= x;
width =y;
}

int area( )
{
return(length * width);
}
}
class AnotherRoom extends Room // inheriting Room
{
int height;
AnotherRoom(int x, int y, int z)
{
super (x,y); // pass values to super class
height=z;
}

2 Prepared By : Sowmya Rani G S, Lecturer, Govt Science College, Chitradurga


OBJECT ORIENTED PROGRAMMING WITH JAVA

int volume( )
{
return (length*width*height);
}
}
class InherTest
{
public static void main(String args[ ] )
{
AnotherRoom room1=new AnotherRoom(14, 12, 10);
int area1= [Link]( ); // superclass method
int volume1 = [Link]( ); // baseclass method
[Link](“Area1= “+area1);
[Link](“Volume=”+volume1);
}
}

Subclass constructor
A subclass constructor is used to construct the instance variables of both the subclass and the superclass.
The subclass constructor uses the keyword super to invoke the constructor method of the superclass. The
keyword super is used subject to the following conditions:

 super may only be used within a subclass constructor method


 The call to superclass constructor must appear as the first statement within the subclass constructor
 The parameters in the super call must match the order and type of the instance variable declaration
in the superclass.

3 Prepared By : Sowmya Rani G S, Lecturer, Govt Science College, Chitradurga


OBJECT ORIENTED PROGRAMMING WITH JAVA

Multilevel Inheritance
A common requirement in object-oriented programming is the use of a derived class as a super class. Java
supports this concept and use it extensively in building its class library.

A Super class

B Intermediate Superclass

C Subclass

Fig : Multilevel Inheritance

The class A serves as a base class for the derived class B which in turn serves as a base class for the derived
class C. The chain ABC is known as inheritance path.

A derived class with multilevel base classes is declared as follows:


class A
{
….
….
}
class B extends A // First level
{

}
class C extends B // Second level
{

4 Prepared By : Sowmya Rani G S, Lecturer, Govt Science College, Chitradurga


OBJECT ORIENTED PROGRAMMING WITH JAVA

Hierarchical Inheritance
Another interesting application of inheritance is to use it as a support to the hierarchical design of a
program. Many programming problems can be cast into a hierarchy where certain features of one level are
shared by many others below the level.

B C D

Fig: Hierarchical inheritance

A derived classes with hierarchical base class is declared as follows:


class A
{
….
….
}
class B extends A
{

}
class C extends A
{

}
class D extends A
{

5 Prepared By : Sowmya Rani G S, Lecturer, Govt Science College, Chitradurga


OBJECT ORIENTED PROGRAMMING WITH JAVA

OVERRIDING METHODS (METHOD OVERRIDING IN JAVA)

If sub class has the same method as declared in the super class it is known as Method Overriding.

Rules for java method overridingc:


1. The method must have the same name as in the super class.
2. The method must have the same parameters as in the super class.
3. The method must have the same return type specifiers of the parameters in the super class.

Program to illustrate the method overriding


class Vehicle{
void run(){[Link]("Vehicle is running");}
}
//Creating a child class
class Bike extends Vehicle{
public static void main(String args[]){
//creating an instance of child class
Bike obj = new Bike();
//calling the method with child class instance
[Link]();
}
}

6 Prepared By : Sowmya Rani G S, Lecturer, Govt Science College, Chitradurga


OBJECT ORIENTED PROGRAMMING WITH JAVA

FINAL VARIABLES AND METHODS AND FINAL CLASS

final Keyword

Java final keyword is a non-access specifier that is used to restrict a class, variable, and method. If we
initialize a variable with the final keyword, then we cannot modify its value.

1. Java final variable:

If we initialize a variable with the final keyword then we cannot modify its value.

Ex: final int SIZE =100;

2. Java final method:

If we declare a method as final, then it cannot be overridden by any subclasses. And, if we declare a class as
final, we restrict the other classes to inherit or extend it.

final void showstatus( );

[Link] final class:

If we declare class as a final. We restrict the other class to inherit or extend it. i.e final classes cannot be
inherited by other classes.

final class Aclass {…….}


final class Bclass extends Someclass {…….}

finalize ( )
finalize is method in java which is used to perform clean up processing just before object is garbage
collected.

7 Prepared By : Sowmya Rani G S, Lecturer, Govt Science College, Chitradurga


OBJECT ORIENTED PROGRAMMING WITH JAVA

ABSTRACT METHODS AND CLASSES


 Abstract method can only be used in an abstract class and it does not have a body. The body is
provided by the sub class.
 Abstract is a restricted class that cannot be used to create objects.
 We can indicate that a method must always be redefined in a subclass, thus making overriding
compulsory. This is done by using the modifier keyword abstract in the method definition.
Ex: abstract class Shape
{
………
abstract void draw( );
……….
……….
}
When a class contains one or more abstract methods, it should also be declared abstract as shown in above.

While using abstract classes, we must satisfy the following conditions:


 We cannot use abstract classes to instantiate objects directly.
Ex: Shape s = new Shape( );
is illegal because shape is an abstract class.
 The abstract methods of an abstract class must be defined in its subclass
 We cannot declare abstract constructor or abstract static methods

Methods with Varargs


Varargs represents variable length arguments in methods, which is one of the features introduced by J2SE
5.0. It makes the java code simple and flexible. Varargs takes the following form:
<access specifier> <static> void method_name(Object …. Arguments)
{

In the above syntax, the method contains an argument called varargs in which object is the type of an
argument, ellipsis ( ) is the key to varargs and arguments is the name of the variables.

8 Prepared By : Sowmya Rani G S, Lecturer, Govt Science College, Chitradurga


OBJECT ORIENTED PROGRAMMING WITH JAVA

VISIBILITY CONTROL
The visibility modifiers is also known as access modifiers. Java provides three types of visibility modifiers:
public, private and protected. They provide different levels of protection.

 public Access: Any variable or method is visible to the entire class in which it is defined. What if
we want to make it visible to all classes outside this class? This is possible by simply declaring the variable
or method as public.
Ex: public int number;
public void sum( )

 friendly Access: In many of our examples, we have not used public modifier, yet they were still
accessible in other classes in the program. When no access modifier is specified, the member defaults to a
limited version of public accessibility known as “friendly” level of access.

The difference between the public access and the friendly access is that the public modifier makes fields
visible in all classes, regardless of their packages while friendly access makes fields visible only in the same
package, but not in other packages. A package is a group of related classes stored separately.

 protected Access: The visibility level of a “protected” fields lies in between the public access and
friendly access. i.e the protected modifier makes the fields visible not only to all classes in the same
package but also to subclasses in other packages. Note-that non-subclasses in other packages cannot access
the “protected” members.

 private: private fields enjoy the highest degree of protection. They 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. It prevents the method from being subclasses.
Also note that we cannot override a non-private method in a subclass and then make it private.

9 Prepared By : Sowmya Rani G S, Lecturer, Govt Science College, Chitradurga


OBJECT ORIENTED PROGRAMMING WITH JAVA

 private protected Access: A field can be declared with two keywords private and protected
together.
private protected int CodeNumber;

This gives the visibility level in between the “protected” access and “private” access. This modifier makes
the fields visible in all subclasses regardless of what package they are in. Remember, these fields are not
accessible by other classes in the same package.

Rules:
Given below are some simple rules for applying appropriate access modifiers.
 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.
 Use “default” if the field is to be visible everywhere in the current package only.
 Use private protected if the field is to be visible only in subclasses, regardless of packages.
 Use private if the field is not to be visible anywhere except in its own class.

10 Prepared By : Sowmya Rani G S, Lecturer, Govt Science College, Chitradurga


OBJECT ORIENTED PROGRAMMING WITH JAVA

PACKAGES: PUTTING CLASSES TOGETHER

Packages are java’s way of grouping a variety of classes and/or interfaces together. The grouping is usually
done according to functionality. In fact, packages acts as “containers” for classes. By organizing our classes
into packages we achieve 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. i.e, 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.
3. Packages provide 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”. First we can design classes and
decide their relationships, and then we can implement the java code needed for the methods. It is
possible to change the implementation of any method without affecting the rest of the design.

Java packages are classified into two types: the first category is known as Java API packages and the second
category is known as user defined packages.

Java API packages


Java API provides a large number of classes grouped into different packages according to functionality. The
below figure shows the functional breakdown of packages that are frequently used in the program. The
below table shows the classes that belong to each package.

Java

lang util io awt net applet

Fig: Frequently used API packages

11 Prepared By : Sowmya Rani G S, Lecturer, Govt Science College, Chitradurga


OBJECT ORIENTED PROGRAMMING WITH JAVA

Java system packages and their classes


Package Name Contents
[Link] Language supports classes. These are classes that java compiler itself uses and
therefore they are automatically imported. They included classes for primitive types,
strings, math functions, threads and exception.
[Link] Language utility classes such as vectors, hash tables, random numbers, date etc
[Link] Input/output support classes. They provide facilities for the input and output of data.
[Link] Set of classes for implementing graphical user interface. They include classes for
windows, buttons, lists, menus and so on.
[Link] classes for networking. They include classes for communicating with local computers
as well as with internet servers.
[Link] classes for creating and implementing applets.

Using System Packages


The packages are organized in a hierarchical structure as illustrated in figure. This shows that the package
named java contains the package awt, which in turn contains various classes required for implementing
graphical user interface.
Java

awt Package containing


awt package
Color

Graphics

package containing
Font
classes
:
classes containing
Image
methods

Fig: Hierarchical representation of [Link] package

12 Prepared By : Sowmya Rani G S, Lecturer, Govt Science College, Chitradurga


OBJECT ORIENTED PROGRAMMING WITH JAVA

There are two ways of accessing classes’ stores in a package. The first approach is to use the fully qualified
class name of the class that we want to use. This is done by using the package name containing the class and
then appending the class name to it using the dot operator. For example: if we want to refer to the class
Color in the awt package, then we may do so as follows.
[Link]
Notice that awt is a package within the package java and the hierarchy is represented by separating the
levels with dots.

We might want to use a class contained in a package. We may achieve this easily as follows:

import [Link];
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 [Link];

imports the class Color and therefore the class name can now be directly used in the program. There is no
need to use the package name to qualify the class.

The second statement imports every class contained in the specified package. For Example, the statement
import [Link].*;

will bring all classes of [Link] package.

13 Prepared By : Sowmya Rani G S, Lecturer, Govt Science College, Chitradurga


OBJECT ORIENTED PROGRAMMING WITH JAVA

Naming Conventions

Packages can be named using the standard java naming rules. By convention, however packages begin with
lowercase letters. This makes it easily for user to distinguish package names from class names when looking
at an explicit reference to a class. We know that all class names, again by convention, begin with an
uppercase letter. For example,
double y= java. lang . Math . sqrt(x);

package class method


name name name

This statement uses a fully qualified class name Math to invoke the method sqrt( ). Note that methods begin
with lowercase letters.

Creating Packages
Now, let us see how to create our own packages. We must first declare the name of the package using the
package keyword followed by a package name. This is must be first statement in a java source file. Then
we define a class, just as we normally define a class.

Here is an example: package firstPackage // package declaration


public class FirstClass // class definition
{
Body of class
}
Here the package name is firstPackage. The class FirstClass is now considered a part of this package. This
listing would be saved as a file called [Link], and located in a directory named firstPackage.
When source file is completed. Java will create a .class file and store it in the same directory.

14 Prepared By : Sowmya Rani G S, Lecturer, Govt Science College, Chitradurga


OBJECT ORIENTED PROGRAMMING WITH JAVA

Creating our own package involves the following steps:


1. Declare the package at the beginning of a file using the form. package
package_name;
2. Define the class that is to be put in the package and declare it public.
3. Create a subdirectory under the directory where the main sources files are stored.
4. Store the listing as the [Link] file in the subdirectory created.
5. Compile the file. This creates .class file in the subdirectory.

Java also supports the concept of package hierarchy. This is done by specifying multiple names in a package
statement, separated by dots. Ex,
package firstPackage . secondPackage;

This approach allows us to group related classes into a package and then group related packages into a
larger package. Remember to store this package in a subdirectory named firstPackage/secondPackage.

Accessing a Package
Java system packages can be accessed either using a fully qualified class name or using a shortcut approach
through the import statement. We use the import statement when there are many references to a particular
package or the package name is too long and unwieldy.

The import statement can be used to search a list of packages for a particular class. The general form of
import statement for searching a class is as follows:
import package1 [.package2] [.package3].classname;

Here package1 is the name of the top level package, package2 is the name of the package that is the explicit
classname is specified.

Note that the statement must be end with a semicolon (;). The import statement should appear before any
class definitions in a source file. Multiple import statements are allowed. The following is an example of
importing a particular class:
import [Link];

15 Prepared By : Sowmya Rani G S, Lecturer, Govt Science College, Chitradurga


OBJECT ORIENTED PROGRAMMING WITH JAVA

Using a Package
The listing below shows a package named package1 containing a single class ClassA.
package package1;
public class ClassA
{
public void display( )
{
[Link](“Class A”);
}
}
This source file should be named as [Link] and stored in the subdirectory package1 as stated earlier.
Now compile this java file. The resultant [Link] will be stored in the same subdirectory.

Now consider the listing shown below:


import [Link];
class PackageTest1
{
public static void main(Sting args[ ])
{
ClassA objectA = new ClassA( );
[Link]( );
}
}

This listing shows a simple program that imports the class ClassA from the package package1. The source
file should be saved as [Link] and then compiled. The source file and the compiled file would
be saved in the directory of which package1 was a subdirectory

16 Prepared By : Sowmya Rani G S, Lecturer, Govt Science College, Chitradurga


OBJECT ORIENTED PROGRAMMING WITH JAVA

Now let us consider another package named package2 containing again a single class as shows below:
package package2;
public class ClassB
{ protected int m=10;
public void displayB( )
{
[Link](“Class B”);
[Link](“ m = “ + m);
} }
As usual, the source file and the compiled file of this package are located in the subdirectory package2.

W a p to illustrate the importing classes from other packages


import [Link];
import package2.*;
class PackageTest2
{
public static void main(String args[ ])
{
ClassA objectA = new ClassA( );
ClassB objectB = new ClassB( );
[Link]( );
[Link]( );
}
}
This program may be saved as [Link], compiled and run to obtain the results. The output will be
as under
Class A
Class B
M=10

17 Prepared By : Sowmya Rani G S, Lecturer, Govt Science College, Chitradurga


OBJECT ORIENTED PROGRAMMING WITH JAVA

Adding class to a package


It is simple to add a class to an existing package. Consider the following package:
package p1;
public ClassA
{
// body of A
}
The package1 contains one public class by name A. suppose we want to add another classB to this package.
This can be done as follows:
1. Define the class and make it public.
2. Place the package statement.
package p1;
before the class definition as follows:
package p1;
public class B
{
// body of B
}
3. Store this [Link] file under the directory p1.
4. Compile [Link] file. This will create a [Link] file and place it in the directory p1.
Note that we can also add a non-public class to a package using the same procedure.
Now, the package p1 will contain both the classes A and B. A statement like
import p1. *;
will import both of them.
If we want to create a package with multiple public classes in it, we may follow the following steps:
1. Decide the name of the package.
2. Create a subdirectory with this name under the directory where main source files are stored.
3. Create classes that are to be placed in the package in separate source files and declare the package
statement package packagename;
at the top of each source file.
4. Switch to the subdirectory created earlier and compile each source file. When completed, the
package would contain .class files of all the source files.

18 Prepared By : Sowmya Rani G S, Lecturer, Govt Science College, Chitradurga


OBJECT ORIENTED PROGRAMMING WITH JAVA

Hiding classes
When we import a package using asterisk ( * ), all public classes are imported. However, we may prefer to
“not import” certain classes. i.e we may like to hide these classes from accessing from outside of the
package. Such classes should be declared “not public”.
Example: package p1;
public class X // public class available outside
{
// body of x
}
class Y
{
// body of Y
}
Here, the class Y which is not declared public is hidden from outside of the package p1. This class can be
seen and used only by other classes in the same package.

Now, consider the following code, which imports the package p1 that contains classes X and Y.
import p1.*;
X objectX; // classX is available here
Y objectY; // Y is not available here

Static import
This feature eliminates the need of qualifying a static member with the class name. The static import
declaration is similar to that of import. We can use the import statement to import classes from packages
and use them without qualifying the package. Similarly, we can use the static import static members from
classes and use them without qualifying the class name.

The syntax for using the static import feature is:


import static package-name . subpackage-name . class-name . staticmember-name;
( or )
import static package-name . subpackage-name . class-name . * ;

19 Prepared By : Sowmya Rani G S, Lecturer, Govt Science College, Chitradurga


OBJECT ORIENTED PROGRAMMING WITH JAVA

Before introducing the static import feature, we had to use the static member with the qualifying classname.
For Example: consider the following code that contains the static member PI;

double area_of_circle = Math . PI * radius * radius;

In the above code, PI is the static member of the class, Math. So the static member PI is used in the above
program with the qualified class name called Math.

W a program to illustrate the use of static import


import static [Link].*;
public class MathOperation
{
public void circle(double r)
{
double area = PI * r * r;
[Link](“The Area Circle is:”+area);
}
public static void main(String args[ ])
{
MathOperation obj = new MathOperation( );
[Link]( 2.3);
}
}

20 Prepared By : Sowmya Rani G S, Lecturer, Govt Science College, Chitradurga

You might also like