JAVA Unit 2
JAVA Unit 2
Inheritance – Inheritance hierarchies super and sub classes, super keyword, preventing
inheritance: final classes and methods, the Object class and its methods. Polymorphism- dynamic
binding, static binding, abstract classes and methods. Interfaces – Interfaces vs. Abstract classes,
defining an interface, Multiple Inheritance through interface, extending interface. Packages-
Defining, Creating and Accessing a Package, Understanding CLASSPATH, importing packages.
Note:
In the Java programming language, each class is allowed to have one direct super class, and each
super class has the potential for an unlimited number of subclasses.
Class: A class is a group of objects which have common properties. It is a template or blueprint
from which objects are created.
Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a
derived class, extended class, or child class.
Super Class/Parent Class: Superclass is the class from where a subclass inherits the features. It
is also called a base class or a parent class.
Reusability: As the name specifies, reusability is a mechanism which facilitates you to reuse the
fields and methods of the existing class when you create a new class. You can use the same
fields and methods already defined in the previous class.
In java programming, multiple and hybrid inheritance is supported through interface only.
We will learn about interfaces later.
Single Inheritance Multilevel Inheritance
class Animal class A{
{ void eat(){System.out.println("eating...");}
void eat() }
{
System.out.println("eating..."); class B extends A{
} void bark(){System.out.println("barking...");}
} }
class Dog extends Animal
{ class C extends B{
void bark() void weep()
{ {System.out.println("weeping...");}
System.out.println("barking..."); }
}
} class Test{
class TestInheritance public static void main(String args[]){
{ C d=new C();
public static void main(String args[]) d.weep();
{ d.bark();
Dog d=new Dog(); d.eat();
d.bark(); }}
d.eat();
}
}
Hierarchical Inheritance multiple Inheritance not supports in java
class A{ class A{
void eat(){System.out.println("eating...");} void msg(){System.out.println("Hello");}
} }
class B extends A{ class B{
void bark(){System.out.println("barking...");} void msg(){System.out.println("Welcome");}
} }
class C extends A{ class C extends A,B{//suppose if it were
void meow()
{System.out.println("meowing...");} public static void main(String args[]){
} C obj=new C();
class TestInheritance3{ obj.msg();//Now which msg() method would
public static void main(String args[]){ be invoked?
C d=new C(); }
d.meow(); }
d.eat();
//d.bark();//C.T.Error
}}
Method Overriding
class Animal
{
void eat()
{
System.out.println("eating...");
}
}
class Dog extends Animal
{
void eat()
{
System.out.println("barking...");
}
}
class TestInheritance
{
public static void main(String args[])
{
Dog d=new Dog();
d.eat();
Animal a=new Animal();
a.eat();
}
}
Super Keyword
The super keyword in Java is a reference variable which is used to refer immediate parent class
object.
The word polymorphism is a combination of two words i.e. ploy and morphs. The word poly
means many and morphs means different forms. In short, a mechanism by which we can
perform a single action in different ways.
Example.
Types of Polymorphism
The parameters are in a different sequence. If one method accepts a string and a long while the
other accepts a long and a string, for example. This form of order, on the other hand, makes it
tough for the API to grasp.
Every method has a different signature due to the differences in parameters. The Java compiler
knows which method is invoked.
Example of static polymorphism
One of the ways by which Java supports static polymorphism is method overloading. An
example showing the case of method overloading in static polymorphism is shown below:
Example:
class SimpleCalculator
{
int add(int a, int b)
{
return a+b;
}
The compiler does not determine the method to be executed in this type of polymorphism in
Java. The process is carried out at runtime by the Java Virtual Machine (JVM). When a call to an
overridden process is resolved at run time, it is referred to as dynamic polymorphism. The
overridden method is called by a superclass's reference variable. While the methods implemented
by both the subclass and the superclass have the same name, they provide separate functionality.
In this process, an overridden method is called through a reference variable of a superclass. The
determination of the method to be called is based on the object being referred to by the reference
variable.
Method Overriding
It provides a specific implementation to a method that is already present in the parent class. it is
used to achieve run-time polymorphism. Remember that, it is not possible to override
the static method. Hence, we cannot override the main() method also because it is a static
method.
We call an overridden method through a reference of the parent class. The type of object decides
which method is to be executed and it is decided by the JVM at runtime.
In the following example, we have created two classes named Sample and Demo. The Sample
class is a parent class and the Demo class is a child or derived class. The child class is
overriding the dispaly() method of the parent class.
We have assigned the child class object to the parent class reference. So, in order to determine
which method would be called, the type of the object would be decided by the JVM at run-time.
It is the type of object that determines which version of the method would be called (not the type
of reference).
class Sample
{
//method of the parent class
public void display()
{
System.out.println("Overridden Method");
}
}
//derived or child class
public class Demo extends Sample
{
//method of child class
public void display()
{
System.out.println("Overriding Method");
}
public static void main(String args[])
{
//assigning a child class object to parent class reference
Sample obj = new Demo();
//invoking display() method
obj.display();
}
}
final keyword: Three uses with final keyword: 2 & 3 are used with
Inheritance
1. To define constants
2. To prevent Method Overriding
3. To prevent Inheritance
class A {
final void meth() {
System.out.println("This is a final method.");
}
}
class B extends A
{
void meth() { // ERROR! Can't override.
System.out.println("Illegal!");
}
}
Because meth( ) is declared as final, it cannot be overridden in B. If we attempt to do so, a
compile-time error will result.
To Prevent Inheritance
To prevent a class from being inherited, declare the class as final. Declaring a class as final
implicitly declares all of its methods as final, too.
final class A
{
//...
}
// The following class is illegal.
class B extends A
{
// ERROR! Can't subclass A
//...
}
Example:
Write a Java program to demonstrate abstract methods and abstract classes.
abstract class Figure {
double dim1;
double dim2;
Figure(double a, double b) {
dim1 = a; dim2 = b;
}
// area is now an abstract method
abstract double area(); //PARTIALLY COMPLETED
}
class Rectangle extends Figure {
Rectangle(double a, double b)
{
super(a, b);
}
// override area for rectangle
double area() {
System.out.println("Inside Area for Rectangle.");
return dim1 * dim2;
}
}
class Triangle extends Figure {
Triangle(double a, double b)
{
super(a, b);
}
// override area for right triangle
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());
}
}
Interfaces
Interfaces are like a 100-percent abstract superclass.
An interface is a contract.
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.
Example:
public interface IntStack
{
void push(int n); int pop();
}
class FixedStack implements IntStack
{
public void push(int n) { } public int pop() { }
}
Interfaces properties
1) Interfaces are implicitly abstract.
2) All interface methods are implicitly public and abstract.
3) All variables defined in an interface must be public, static, and final
4) Because interface methods are abstract, they cannot be marked final.
5) An interface can extend one or more other interfaces.
6) An interface can’t extend anything except another interface.
7) An interface cannot implement another interface or class.
8) An interface must be declared with the keyword interface.
9) Interface types can be used polymorphically .
Extending Interfaces
One interface can inherit another by use of the keyword extends. The syntax is the
same as for inheriting classes.
When a class implements an interface that inherits another interface, it must
provide implementations for all methods required by the interface inheritance
chain.
interface Printable{
void print();
}
interface Showable{
void show();
}
Ex 1:
interface Printable{
void print();
}
interface Showable{
void print();
}
Ex 2:
File: TestInterface1.java
Output:
drawing circle
Ex 3:
File: TestInterface2.java
interface Bank{
float rateOfInterest();
}
class SBI implements Bank{
public float rateOfInterest(){return 9.15f;}
}
class PNB implements Bank{
public float rateOfInterest(){return 9.7f;}
}
class TestInterface2{
public static void main(String[] args){
Bank b=new SBI();
System.out.println("ROI: "+b.rateOfInterest());
}}
Abstract class vs interface
Abstract class contains abstract and non- Interfaces do not contain non-abstract methods
abstract methods. but it contains only abstract methods
The abstract keyword is used to The interface keyword is used to
declare abstract class. declare interface.
Abstract methods contains instance variables and Interfaces do not contain instance variables, it
constants. contains only constants.
Abstract methods needs to be declared as abstract All methods are implicitly public and abstract.
explicitly.
An abstract class can be extended An interface can be implemented using
using keyword "extends". keyword "implements".
Abstract class can extends another class, not An interface can extends another interfaces only,
interfaces not classes
An abstract class can implement an interface An interface cannot implement another interface or
class.
Ex: Ex:
abstract class A{ } interface Bounceable
Packages
A package is a grouping of related classes and interfaces.
Benefits of packages:
Packages provides -
✓ We can allow types within the package to have unrestricted access to one another yet still
a) access protection
✓ The names of one package types won’t conflict with the types in other packages.
b) Name space management.
c) Two different programmers can easily determine the types defined in the package are related.
✓ The package statement (for example, package graphics;) must be the first line in the source
package pkg; -> Here, pkg is the name of the package.
✓ There can be only one package statement in each source file, and it applies to all types in the
file.
Multilevel Packages
We can create a hierarchy of packages. To do so, simply separate each package name from the
one above it by use of a period.
Package categories
Two forms:
Built-in package:
➢ All of the standard Java classes included with Java are stored in a package called java.
➢ The basic language functions are stored in a package inside of the java package called
java.lang.
User-defined package:
User defined packages are the packages defined by the programmers specific to their
application.
Ex: package edu.cbit.example;
Access Protection in Java using Packages
In addition to the access modifiers (private,public,protected and default), packages will add
another dimension to access control.
Java addresses four categories of visibility for class members:
1. Subclasses in the same package
2. Non-subclasses in the same package
3. Subclasses in different packages
4. Classes that are neither in the same package nor subclasses
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
How to compile java package
The import keyword is used to make the classes and interface of another package accessible to
the current package.
Example of package that import the packagename.*
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
2) Using packagename.classname
If you import package.classname then only declared class of this package will be accessible.
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.A;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
//save by B.java
package mypack;
class B{
public static void main(String args[]){
pack.A obj = new pack.A();//using fully qualified name
obj.msg();
}
CLASSPATH
The CLASSPATH refers to the path on your file system where your .class files are saved, and
the classpath is defined by the CLASSPATH environment variable.
The CLASSPATH environment variable specifies the directories where you want the compiler
and the JVM to search for bytecode.
Finding Packages
How does the Java run-time system know where to look for packages that we create?
1. First, by default, the Java run-time system uses the current working directory as its starting
point. Thus, if our package is in a subdirectory of the current directory, it will be found.
2. We can specify a directory path or paths by setting the CLASSPATH environmental variable.
3. we can use the -classpath option with java and javac to specify the path to your classes.
Using the - classpath flag overrides the CLASSPATH environment variable.