Java Programming UNIT 2 Notes
Java Programming UNIT 2 Notes
UNIT –II
INHERITANCE:
Inheritance can be defined as the process where one object acquires the properties of
another.
With the use of inheritance the information is made manageable in a hierarchical order.
In the terminology of Java, a class that is inherited is called a super class.
The class that does the inheriting is called a subclass. Therefore, a subclass is a
specialized version of a super class. It inherits all of the instance variables and methods
defined by the super class and add its own, unique elements.
The most commonly used keyword would be extends and implements. These words
would determine whether one object IS-A type of another. By using these keywords we
can make one object acquire the properties of another object.
The general form of a class declaration that inherits a super class is shown here:
class subclass-name extends super class-name {
// body of class
}
The following kinds of inheritance are there in java.
Single Inheritance
Multilevel Inheritance (Inheritance Hierarchy)
Java does not support multiple Inheritance
Multiple Inheritance: The mechanism of inheriting the features of more than one base
class into a single class is known as multiple inheritance.
The multiple inheritance can be achieved by using the interface.
In Java Multiple Inheritance can be achieved through use of Interfaces by implementing
more than one interfaces in a class.
SINGLE INHERITANCE:
When a subclass is derived simply from it's parent class then this mechanism is known as
simple inheritance.
In case of simple inheritance there is only a sub class and it's parent class. It is also called
as one level inheritance.
Eg:
class A {
int i, j;
void showij() {
System.out.println("i and j: " + i + " " + j);
}
}
class B extends A { // Create a subclass by extending class A.
int k;
void showk() {
System.out.println("k: " + k);
}
void sum() {
System.out.println("i+j+k: " + (i+j+k));
}
}
class SimpleInheritance {
public static void main(String args[]) {
A superOb = new A();
B subOb = new B();
superOb.i = 10;
superOb.j = 20;
System.out.println("Contents of superOb: ");
superOb.showij();
System.out.println();
subOb.i = 7; // subclass has access to all public members of its superclass
subOb.j = 8;
subOb.k = 9;
System.out.println("Contents of subOb: ");
subOb.showij();
subOb.showk();
System.out.println();
System.out.println("Sum of i, j and k in subOb:");
subOb.sum();
}
}
Note:
A class member that has been declared as private will remain private to its class. It is not
accessible by any code outside its class, including subclasses.
Eg 2:
class Box {
double width, height ,depth;
Box(Box ob) { // construct clone of an object & pass object to constructor
width = ob.width;
height = ob.height;
depth = ob.depth;
}
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
Box() {
width = -1; // use -1 to indicate
height = -1; // an uninitialized
depth = -1; // box
}
Box(double len) {
width = height = depth = len;
}
double volume() {
return width * height * depth;
}
}
class BoxWeight extends Box {
double weight; // weight of box
BoxWeight(double w, double h, double d, double m) {
width = w;
height = h;
depth = d;
weight = m;
}
}
class DemoBoxWeight {
public static void main(String args[]) {
BoxWeight mybox1 = new BoxWeight(10, 20, 15, 34.3);
BoxWeight mybox2 = new BoxWeight(2, 3, 4, 0.076);
double vol;
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
System.out.println("Weight of mybox1 is " + mybox1.weight);
System.out.println();
vol = mybox2.volume();
System.out.println("Volume of mybox2 is " + vol);
System.out.println("Weight of mybox2 is " + mybox2.weight);
} }
Once a super class is created that defines the general aspects of an object , that super class
can be inherited to form specialized classes.
Each sub class simply adds its own, unique attributes. i.e) inheritance provides reusability
of code.
Multilevel Inheritance:
When a subclass is derived from a derived class then this mechanism is known as the
multilevel inheritance. The derived class is called the subclass or child class for it's parent
class and this parent class works as the child class for it's just above ( parent ) class.
Eg:
class student
{
int roll;
void get(int a)
{
roll =a;
System.out.println(roll);
}
}
class test extends student
{ int m1,m2,m3;
super keyword:
The super is java keyword. As the name suggest super is used to access the members of
the super class. It is used for two purposes in java.
The first use of keyword super is to access the hidden data variables of the super class
hidden by the sub class.
E.g. Suppose class A is the super class that has two instance variables as int a and float b.
class B is the subclass that also contains its own data members named a and b. then we
can access the super class (class A) variables a and b inside the subclass class B just by
calling the following command.
super.member;
Here member can either be an instance variable or a method. This form of super most
useful to handle situations where the local members of a subclass hides the members of a
super class having the same name. The following example clarify all the confusions.
class A{
int a;
float b;
void Show(){
System.out.println("b in super class: " + b);
}
}
class B extends A{
int a;
float b;
B( int p, float q){
a = p;
super.b = q;
}
void Show(){
super.Show();
System.out.println("b in super class: " + super.b);
System.out.println("a in sub class: " + a);
}
public static void main(String[] args){
B subobj = new B(1, 5);
subobj.Show();
}
}
Output:
C:\>java B
b in super class: 5.0
b in super class: 5.0
a in sub class: 1
Ex 2:
class A {
int i;
}
class B extends A {
int i; // this i hides the i in A
B(int a, int b) {
super.i = a; // i in A
i = b; // i in B
}
void show() {
System.out.println("i in superclass: " + super.i);
System.out.println("i in subclass: " + i);
}
}
class UseSuper {
public static void main(String args[]) {
B subOb = new B(1, 2);
subOb.show();
}
}
This program displays the following:
i in superclass: 1
i in subclass: 2
Executive
Eg: multi level inheritance program.
Here Employee is the super class . Manager, Secretary and Programmer are the sub
classes of Employee class. Executive is a sub class of Manager class
Eg 2: Inheritance hierarchy for the frame and component classes in AWT
object
component
container
window
Jcomponent
frame
jpanel
jframe
Access Specifiers:
Access specifiers allows the programmer to control the visibility of class members.
Java allows you to control access to classes, methods, and fields via access specifiers.
Java supplies a rich set of acess specifiers.some aspects of access control are related mostly to
inheritance or packages(grouping of classes)
- Private
- Public
- Protected
- Default
Public:
The only constraint is that a file with Java source code can only contain one public class whose
name must also match with the filename. If it exists, this public class represents the application
or the applet, in which case the public keyword is necessary to enable the Web browser or
appletviewer to show the applet.
Eg:
// code
Protected:
Protected methods and fields can only be accessed within the same class to which the methods
and fields belong, within its subclasses, and within classes of the same package, but not from
anywhere else.
The protected access level is used when it is appropriate for a class's subclasses to have access
to the method or field, but not for unrelated classes.
If you do not set access to specific level, then such a class, method, or field will be accessible
from inside the same package to which the class, method, or field belongs, but not from outside
this package. This access-level is convenient if you are creating packages.
Private:
Private methods and fields can only be accessed within the same class to which the methods
and fields belong.
Private methods and fields are not visible within subclasses and are not inherited by subclasses.
So, the private access specifier is opposite to the public access specifier.
It is mostly used for encapsulation: data are hidden within the class and accessor methods are
provided.
An example, in which the position of the upper-left corner of a square can be set or obtained by
accessor methods, but individual coordinates are not accessible to the user.
this.x = x;
this.y = y;
Private Y
protected Y Y Y
public Y Y Y Y
(none)default Y Y
Accessible to class
yes yes yes no
from same package?
Note:
The difference between the default access which is in fact more restricted than the protected
access. Without access specifier (the default choice), methods and variables are accessible only
within the class that defines them and within classes that are part of the same package. They
are not visible to subclasses unless these are in the same package. protected methods and
variables are visible to subclasses regardless of which package they are in.
INTERFACE:
An interface in Java is a blueprint of a class. It has static constants and abstract methods.
The interface in Java is a mechanism to achieve abstraction. There can be only abstract methods
in the Java interface, not method body. It is used to achieve abstraction and multiple inheritance
in Java.
In other words, you can say that interfaces can have abstract methods and variables. It cannot
have a method body.
An interface is declared by using the interface keyword. It provides total abstraction; means all
the methods in an interface are declared with the empty body, and all the fields are public, static
and final by default. A class that implements an interface must implement all the methods
declared in the interface.
Syntax:
1. interface <interface_name>{
2.
3. // declare constant fields
4. // declare methods that abstract
5. // by default.
6. }
Internal addition by the compiler
In other words, Interface fields are public, static and final by default, and the methods are public
and abstract.
Output:
Hello
File: TestInterface1.java
File: TestInterface2.java
1. interface Bank{
2. float rateOfInterest();
3. }
4. class SBI implements Bank{
5. public float rateOfInterest(){return 9.15f;}
6. }
7. class PNB implements Bank{
8. public float rateOfInterest(){return 9.7f;}
9. }
10. class TestInterface2{
11. public static void main(String[] args){
12. Bank b=new SBI();
13. System.out.println("ROI: "+b.rateOfInterest());
14. }}
POLYMORPHISM:
Refers to an object’s ability to behave differently depending on its type
Poly = ‘many’
morph = ‘form’
An operation may exhibit different behaviors in different instances.
Example: +operator will produce a sum when the operands are numerals and a third
string when the operands are strings.
1+2=3
‘Kc’+’tech’=’kctech’
Making an operator to exhibit different behavior is referred as operator overloading
Two types of polymorphism:
Static Polymorphism
Eg: Overloading
Run Time Polymorphism
Eg: overriding and dynamic method binding
Method Overloading:
Practice of using same method name to denote several different operations
Overloaded methods are methods with the same name signature but either a different
number of parameters or different types in the parameter list.
Method overloading is a static polymorphism.
For example, consider a class String which is designed to simplify string operations
Append functions are overloaded to accept different types of data
One Append function appends an integer value to string, another Append function
appends a float value
void Append(int)
void Append(float)
The appropriate function will be invoked based on the type of the argument used in the
function call
Any number of functions can have the same name as long as they differ in any one of the
following
Type of arguments
Number of arguments
Eg Program : [ refer unit I notes]
Method overriding:
Redefining a base class method in a sub class is called method overriding
They have the same signature and the subclass definition is used.
In a class hierarchy, when a method in a subclass has the same name and type signature
as a method in its superclass, then the method in the subclass is said to override the
method in the superclass.
When an overridden method is called from within a subclass, it will always refer to the
version of that method defined by the subclass.
The version of the method defined by the superclass will be hidden.
An overriding method can call an overridden method using the syntax
super.methodName()
Note: static methods cannot be over riden
Eg:
class A {
int i, j;
A(int a, int b) {
i = a;
j = b;
}
void show() {
System.out.println("i and j: " + i + " " + j);
}
}
class B extends A {
int k;
B(int a, int b, int c) {
super(a, b);
k = c;
}
void show() {
System.out.println("k: " + k);
}
}
class Override {
public static void main(String args[]) {
B subOb = new B(1, 2, 3);
subOb.show(); // this calls show() in B
}
}
The output produced by this program is shown here:
k: 3
Eg 2:
class A {
int i;
A(int a, int b) {
i = a+b;
}
void add() {
System.out.println("Sum of a and b is: " + i);
}
}
class B extends A {
int j;
B(int a, int b, int c) {
super(a, b);
j = a+b+c;
}
void add() {
super.add();
System.out.println("Sum of a, b and c is: " + j);
}
}
class MethodOverriding {
public static void main(String args[]) {
B b = new B(10, 20, 30);
b.add();
}
}
Output:
Overloading Overriding
Signature has to be different. Just a difference Signature has to be the same. (including the
in return type is not enough return type)
Accessibility may vary freely. Overriding methods cannot be more private
than the overridden methods.
Exception list may vary freely. Overriding methods may not throw more
checked exceptions than the overridden
methods.
Just the name is reused. Methods are Related directly to sub-classing. Overrides the
independent methods. Resolved at compile- parent class method. Resolved at run-time
time based on method signature. based on type of the object.
Can call each other by providing appropriate Overriding method can call overridden method
argument list. by super.methodName(), this can be used only
to access the immediate super-class's method.
super.super won't work. Also, a class outside
the inheritance hierarchy can't use this
technique.
Methods can be static or non-static. Since the static methods don't participate in overriding,
methods are independent, it doesn't matter. But since they are resolved at compile time based
if two methods have the same signature, on the type of reference variable. A static
declaring one as static and another as non- method in a sub-class can't use 'super' (for the
static does not provide a valid overload. It's a same reason that it can't use 'this' for)
compile time error.
Remember that a static method can't be
overridden to be non-static and a non-static
method can't be overridden to be static. In
other words, a static method and a non-static
method cannot have the same name and
signature (if signatures are different, it would
have formed a valid overload)
There's no limit on number of overloaded Each parent class method may be overridden at
methods a class can have. most once in any sub-class. (That is, you
cannot have two identical methods in the same
class)
Final Keyword:
1. To declare a constant:
Eg: final int a=5;
2. To prevent inheritance
Eg: final class sup
{
// body
}
Class sub extends sup // not possible
{ }
A class declared as final can’t be inherited by other classes.
Declaring a class as final implicitly declares all of its methods as final, too.
Abstract Classes:
There are situations in which you will want to define a superclass that declares the
structure of a given abstraction without providing a complete implementation of every
method.
That is, sometimes you will want to create a superclass that only defines a generalized
form that will be shared by all of its subclasses, leaving it to each subclass to fill in the
details.
Such a class determines the nature of the methods that the subclasses must implement.
A super class that only defines a generalized form that will be shared by all of its
subclasses, leaving it to each subclass to fill in the details is called an abstract class.
An abstract class just specifies what to do and not how to do it
abstract method:
Certain methods be overridden by subclasses by specifying the abstract type modifier.
These methods are sometimes referred to as subclasser responsibility because they have
no implementation specified in the superclass.
Thus, a subclass must override them—it cannot simply use the version defined in the
superclass.
To declare an abstract method, use this general form:
abstract type name(parameter-list);
No method body is present.
Any class that contains one or more abstract methods must also be declared abstract.
To declare a class abstract,
simply use the abstract keyword in front of the class keyword at the beginning of
the class declaration.
Eg : abstract class sample
{
// body
}
There can be no objects of an abstract class.
That is, an abstract class cannot be directly instantiated with the new operator.
Such objects would be useless, because an abstract class is not fully defined.
Also, you cannot declare abstract constructors, or abstract static methods.
Any subclass of an abstract class must either implement all of the abstract methods in the
superclass, or be itself declared abstract.
Example:
abstract class A
{
abstract void callme();
void callmetoo() { // concrete methods are still allowed in abstract classes
System.out.println("This is a concrete method.");
}
}
class B extends A {
void callme() {
System.out.println("B's implementation of callme.");
}
}
class AbstractDemo {
public static void main(String args[]) {
B b = new B();
b.callme();
b.callmetoo();
}
}
Although abstract classes cannot be used to instantiate objects, they can be used to create
object references, because Java's approach to run-time polymorphism is implemented
through the use of superclass references. Thus, it must be possible to create a reference to
an abstract class so that it can be used to point to a subclass object.
Eg:
abstract class Figure {
double dim1;
double dim2;
Figure(double a, double b) {
dim1 = a;
dim2 = b;
}
abstract double area();
}
class Rectangle extends Figure {
Rectangle(double a, double b) {
super(a, b);
}
double area() {
System.out.println("Inside Area for Rectangle.");
return dim1 * dim2;
}
}
class Triangle extends Figure {
Triangle(double a, double b) {
super(a, b);
}
double area() {
System.out.println("Inside Area for Triangle.");
return dim1 * dim2 / 2;
}
}
class AbstractAreas {
public static void main(String args[]) {
// Figure f = new Figure(10, 10); // illegal now
Rectangle r = new Rectangle(9, 5);
Triangle t = new Triangle(10, 8);
Figure figref; // this is OK, no object is created
figref = r;
System.out.println("Area is " + figref.area());
figref = t;
System.out.println("Area is " + figref.area());
}
}
PACKAGES:
two of Java's most innovative features: packages and interfaces
In general, a Java source file can contain any (or all) of the following four internal parts:
A single package statement (optional)
Any number of import statements (optional)
A single public class declaration (required)
Any number of classes private to the package (optional)
A package is a collection of related classes and interfaces in Java
Packages are containers for classes that are used to keep the class name space
compartmentalized.
Packages help in logical grouping of classes and interfaces
All the classes and interfaces that are used for performing I/O operations can be
placed in the same package
All the classes and interfaces that are used for writing network programs can be
placed in the same package
Packages are stored in a hierarchical manner and are explicitly imported into new class
definitions.
Java provides a mechanism for partitioning the class name space into more manageable
chunks. This mechanism is the package.
The package is both a naming and a visibility control mechanism.
We can define classes inside a package that are not accessible by code outside that
package.
Class members can also be defined that are only exposed to other members of the same
package.
Packages allow the classes to have intimate knowledge of each other, but not expose that
knowledge to the rest of the world.
CREATING A PACKAGE
Simply include a package command as the first statement in a Java source file.
Any classes declared within that file will belong to the specified package.
The package statement defines a name space in which classes are stored.
Eg:
Create a folder pack
Place the following program in this folder
Syntax for defining a package:
Package <package name>
Eg: package pack;
Java uses file system directories to store packages.
More than one file can include the same package statement.
The package statement simply specifies to which package the classes defined in a file
belong.
To create a hierarchy of packages. The general form of a multileveled package statement
is shown here:
package pkg1[.pkg2[.pkg3]];
Eg: java.awt.image;
IMPORTING A CLASS
It is difficult to use the fully qualified name of a class through out the program
The import statement can be used to import a class into a program so that the class name
need not be fully qualified
Syntax: import <package name>.<class name>;
Eg: import pack.stack;
/*Spackage.java*/
import pack.Stack;
class StackPackage
{
public static void main(String args[])
{
Stack mystack1 = new Stack();
for(int i=0; i<10; i++)
mystack1.push(i); // push some numbers onto the stack
System.out.println("Stack in mystack1:"); // pop those numbers off the stack
for(int i=0; i<10; i++)
System.out.println(mystack1.pop());
}
}
USES OF PACKAGES
Logical grouping of classes and interfaces
Avoiding clash of names
Provides an extra level of protection to its members
Classes can be reused easily
STANDARD JAVA PACKAGES
java.lang
Contains classes that form the basis of the design of the Java programming
language
No need to explicitly import this package
The String class, System class etc, belong to this package
java.io
Classes and interfaces to perform I/O operations
java.util
Utility classes and interfaces like List, Calendar etc
java.awt
Classes and interfaces to create GUI