Oops - Unit II Inheritance
Oops - Unit II Inheritance
1
System.out.println("a and b: " + a + " " + b);
}
// overload test for a double parameter
double test(double a)
{
System.out.println("double a: " + a);
return a*a;
}
}
class Overload
{
public static void main(String args[])
{
OverloadDemo ob = new OverloadDemo();
double result;
// call all versions of test()
ob.test();
ob.test(10);
ob.test(10, 20);
result = ob.test(123.25);
System.out.println("Result of ob.test(123.25): " + result);
}
}
This program generates the following output:
No parameters
a: 10
a and b: 10 20
double a: 123.25
Result of ob.test(123.25): 15190.5625
2.1.1 Overloading Constructors
you can also overload constructor methods
class Box {
double width;
double height;
double depth;
// constructor used when all dimensions specified
Box(double w, double h, double d) {
width = w;
2
height = h;
depth = d;
}
// constructor used when no dimensions specified
Box() {
width = -1; // use -1 to indicate
height = -1; // an uninitialized
depth = -1; // box
}
// constructor used when cube is created
Box(double len) {
width = height = depth = len;
}
// compute and return volume
double volume() {
return width * height * depth;
}
}
class OverloadCons {
public static void main(String args[]) {
// create boxes using the various constructors
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Box mycube = new Box(7);
double vol;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume of mybox2 is " + vol);
// get volume of cube
vol = mycube.volume();
System.out.println("Volume of mycube is " + vol);
}
}
The output produced by this program is shown here:
Volume of mybox1 is 3000.0
Volume of mybox2 is -1.0
3
Volume of mycube is 343.0
2.2 Using Objects as Parameters
It is both correct and common to pass objects to methods.
// Objects may be passed to methods.
class Test
{
int a, b;
Test(int i, int j)
{
a = i;
b = j;
}
// return true if o is equal to the invoking object
boolean equals(Test o)
{
if(o.a == a && o.b == b)
return true;
else
return false;
}
}
class PassOb
{
public static void main(String args[])
{
Test ob1 = new Test(100, 22);
Test ob2 = new Test(100, 22);
Test ob3 = new Test(-1, -1);
System.out.println("ob1 == ob2: " + ob1.equals(ob2));
System.out.println("ob1 == ob3: " + ob1.equals(ob3));
}
}
This program generates the following output:
ob1 == ob2: true
ob1 == ob3: false
2.3 Returning Objects
A method can return any type of data, including class types that you create.
// Returning an object.
4
class Test
{
int a;
Test(int i)
{
a = i;
}
Test incrByTen()
{
Test temp = new Test(a+10);
return temp;
}
}
class RetOb
{
public static void main(String args[])
{
Test ob1 = new Test(2);
Test ob2;
ob2 = ob1.incrByTen();
System.out.println("ob1.a: " + ob1.a);
System.out.println("ob2.a: " + ob2.a);
ob2 = ob2.incrByTen();
System.out.println("ob2.a after second increase: " + ob2.a);
}
}
The output generated by this program is shown here:
ob1.a: 2
ob2.a: 12
ob2.a after second increase: 22
2.4 Static, Nested and Inner Classes
INNER CLASSES
Inner class means one class which is a member of another class. There are basically four types of
inner classes in java.
1) Nested Inner class
2) Method Local inner classes
3) Anonymous inner classes
4) Static nested classes
5
Nested Inner class
Nested Inner class can access any private instance variable of outer class. Like any other instance
variable, we can have access modifier private, protected, public and default modifier. Like class,
interface can also be nested and can have access specifiers.
Example:
class Outer
{
// Simple nested inner class class Inner
{
public void show()
{
System.out.println("In a nested class method");
}
}
}
class Main
{
public static void main(String[] args)
{
Outer.Inner in = new Outer().new Inner();
in.show();
}
}
Output:
In a nested class method
Method Local inner classes
Inner class can be declared within a method of an outer class.
In the following example, Inner is an inner class in outerMethod().
Example:
class Outer
{
void outerMethod()
{
System.out.println("inside outerMethod");
// Inner class is local to outerMethod()
class Inner
{
void innerMethod()
{
System.out.println("inside innerMethod");
6
}
}
Inner y = new Inner();
y.innerMethod();
}
}
class MethodDemo
{
public static void main(String[] args)
{
Outer x = new Outer();
x.outerMethod();
}
}
Output:
Inside outerMethod
Inside innerMethod
Static nested classes
Static nested classes are not technically an inner class.
They are like a static member of outer class.
Example:
class Outer
{
private static void outerMethod()
{
System.out.println("inside outerMethod");
}
// A static inner class
static class Inner
{
public static void main(String[] args)
{
System.out.println("inside inner class Method");
outerMethod();
}
}
}
Output:
inside inner class Method inside outerMethod
Anonymous inner classes
7
Anonymous inner classes are declared without any name at all. They are created in two ways.
a) As subclass of specified type
class Demo
{
void show()
{
System.out.println("i am in show method of super class");
}
}
class Flavor1Demo
{
// An anonymous class with Demo as base class
static Demo d = new Demo()
{
void show()
{
super.show();
System.out.println("i am in Flavor1Demo class");
}
};
public static void main(String[] args)
{
d.show();
}
}
Output:
i am in show method of super class
i am in Flavor1Demo class
In the above code, we have two class Demo and Flavor1Demo. Here demo act as super class and
anonymous class acts as a subclass, both classes have a method show().
In anonymous class show() method is overridden.
b) As implementer of the specified interface
Example:
class Flavor2Demo
{
// An anonymous class that implements Hello interface
static Hello h = new Hello()
{
public void show()
{
8
System.out.println("i am in anonymous class");
}
};
public static void main(String[] args)
{
h.show();
}
}
interface Hello
{
void show();
}
Output:
i am in anonymous class
In above code we create an object of anonymous inner class but this anonymous inner class is an
implementer of the interface Hello. Any anonymous inner class can implement only one interface
at one time. It can either extend a class or implement interface at a time.
2.5 Inheritance Basics
Inheritance can be defined as the procedure or mechanism of acquiring all the properties
and behaviors of one class to another, i.e., acquiring the properties and behavior of child
class from the parent class.
Types of inheritance in java: single, multilevel and hierarchical inheritance.
Multiple and hybrid inheritance is supported through interface only.
Syntax:
class subClass extends superClass
{
//methods and fields
}
9
SINGLE INHERITANCE
In Single Inheritance one class extends another class (one class only).
Example:
public class ClassA
{
public void dispA()
{
System.out.println("disp() method of ClassA");
}
}
public class ClassB extends ClassA
{
public void dispB()
{
System.out.println("disp() method of ClassB");
}
public static void main(String args[])
{
ClassB b = new ClassB();
b.dispA();
b.dispB();
}
Output
disp() method of ClassA
disp() method of ClassB
10
MULTILEVEL INHERITANCE
In Multilevel Inheritance, one class can inherit from a derived class. Hence, the
derived class becomes the base class for the new class.
Example:
public class ClassA
{
public void dispA()
{
System.out.println("disp() method of ClassA");
}
}
public class ClassB extends ClassA
{
public void dispB()
{
System.out.println("disp() method of ClassB");
}
}
public class ClassC extends ClassB
{
public void dispC()
{
System.out.println("disp() method of ClassC");
}
public static void main(String args[])
{
ClassC c = new ClassC();
c.dispA();
c.dispB();
c.dispC();
}
}
Output
disp() method of ClassA
disp() method of ClassB
disp() method of ClassC
HIERARCHICAL INHERITANCE
11
In Hierarchical Inheritance, one class is inherited by many sub classes.
Example:
public class ClassA
{
public void dispA()
{
System.out.println("disp() method of ClassA");
}
}
public class ClassB extends ClassA
{
public void dispB()
{
System.out.println("disp() method of ClassB");
}
}
public class ClassC extends ClassA
{
public void dispC()
{
System.out.println("disp() method of ClassC");
}
}
public class ClassD extends ClassA
{
public void dispD()
{
System.out.println("disp() method of ClassD");
}
}
public class HierarchicalInheritanceTest
{
public static void main(String args[])
{
ClassB b = new ClassB();
b.dispB();
b.dispA();
ClassC c = new ClassC();
12
c.dispC();
c.dispA();
ClassD d = new ClassD();
d.dispD();
d.dispA();
}
}
Output
disp() method of ClassB
disp() method of ClassA
disp() method of ClassC
disp() method of ClassA
disp() method of ClassD
disp() method of ClassA
class ParentClass
{
public ParentClass()
{
System.out.println("Parent Class default Constructor");
}
}
public class SubClass extends ParentClass
{
SubClass()
{
super();
13
System.out.println("Child Class default Constructor");
}
public static void main(String args[])
{
SubClass s = new SubClass();
}
}
Output:
Parent Class default Constructor
Child Class default Constructor
14
}
}
public class SubClass extends ParentClass
{
public void show()
{
Super.disp();
}
public static void main(String args[])
{
SubClass s = new SubClass();
s.show();
}
}
Output:
Parent Class method
15
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();
}
}
The output produced by this program is shown here:
k: 3
16
void callme()
{
System.out.println("Inside B's callme method");
}
}
class C extends A {
// override callme()
void callme()
{
System.out.println("Inside C's callme method");
}
}
class Dispatch
{
public static void main(String args[])
{
A a = new A(); // object of type A
B b = new B(); // object of type B
C c = new C(); // object of type C
A r; // obtain a reference of type A
r = a; // r refers to an A object
r.callme(); // calls A's version of callme
r = b; // r refers to a B object
r.callme(); // calls B's version of callme
r = c; // r refers to a C object
r.callme(); // calls C's version of callme
}
}
The output from the program is shown here:
Inside A’s callme method
Inside B’s callme method
Inside C’s callme method
2.9 Abstract Classes
You can require that certain methods be overridden by subclasses by specifying the abstract
type modifier.
These methods are some times referred to as subclasser responsibility because they have no
implementation specified in the superclass.
17
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);
FINAL KEYWORD
18
Final keyword can be used along with variables, methods and classes.
1) final variable
2) final method
3. final class
A final variable is a variable whose value cannot be changed at anytime once assigned, it
remains as a constant forever.
Example:
public class Travel
{
final int SPEED=60;
void increaseSpeed()
{
SPEED=70;
}
public static void main(String args[])
{
Travel t=new Travel();
t.increaseSpeed();
}
}
Output :
Exception in thread "main" java.lang.Error: Unresolved compilation problem: The final field
Travel.SPEED cannot be assigned
The above code will give you Compile time error, as we are trying to change the value of a
final variable ‘SPEED’.
Using final to Prevent Overriding
Methods declared as final cannot be overridden. The following fragment illustrates final:
class A
{
final void meth()
{
System.out.println("This is a final method.");
}
}
class B extends A
{
19
void meth()
{ // ERROR! Can't override.
System.out.println("Illegal!");
}
}
2.11 PACKAGES
A java package is a group of similar types of classes, interfaces and sub-packages.
Package in java can be categorized in two form, built-in package and user-defined package.
There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
Advantage of Java Package
1) Java package is used to categorize the classes and interfaces so that they can be easily
maintained.
2) Java package provides access protection.
3) Java package removes naming collision.
Defining a Package
To create a package 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. If package statement is omitted,
the class names are put into the default package, which has no name.
Syntax:
package <fully qualified package name>;
package pkg;
20
Here, pkg is the name of the package. For example, the following statement creates a package
called MyPackage.
package MyPackage;
Java uses file system directories to store packages. For example, the .class files for any classes
you declare to be part of MyPackage must be stored in a directory called MyPackage.
It is possible to create a hierarchy of packages. The general form of a multileveled package
statement is shown here:
package pkg1[.pkg2[.pkg3]];
A package hierarchy must be reflected in the file system of your Java development system. For
example, a package declared as
package java.awt.image;
needs to be stored in java\awt\image in a Windows environment.
We cannot rename a package without renaming the directory in which the classes are stored.
Finding Packages and CLASSPATH
First, by default, the Java run-time system uses the current working directory as its starting
point. Thus, if your package is in a subdirectory of the current directory, it will be found.
Second, you can specify a directory path or paths by setting the CLASSPATH environmental
variable. Third, you can use the - classpath option with java and javac to specify the path to
your classes.
consider the following package specification:
package MyPack
In order for a program to find MyPack, one of three things must be true. Either the program
can be executed from a directory immediately above MyPack, or the CLASSPATH must be
21
set to include the path to MyPack, or the -classpath option must specify the path to MyPack
when the program is run via java.
When the second two options are used, the class path must not include MyPack, itself. It must
simply specify the path to MyPack. For example, in a Windows environment, if the path to
MyPack is C:\MyPrograms\Java\MyPack
then the class path to MyPack is C:\MyPrograms\Java
Example:
// A simple package
package MyPack;
class Balance
{
String name; double bal;
Balance(String n, double b)
{
name = n;
bal = b;
}
void show()
{
if(bal<0)
System.out.print("--> ");
System.out.println(name + ": $" + bal);
}
}
class AccountBalance
{
public static void main(String args[])
{
Balance current[] = new Balance[3];
current[0] = new Balance("K. J. Fielding", 123.23);
current[1] = new Balance("Will Tell", 157.02);
current[2] = new Balance("Tom Jackson", -12.33);
for(int i=0; i<3; i++)
current[i].show();
}
}
Call this file AccountBalance.java and put it in a directory called MyPack.
Next, compile the file. Make sure that the resulting .class file is also in the MyPack
directory. Then, try executing the AccountBalance class, using the following command line:
22
java MyPack.AccountBalance
Remember, you will need to be in the directory above MyPack when you execute this
command. (Alternatively, you can use one of the other two options described in the preceding
section to specify the path MyPack.)
As explained, AccountBalance is now part of the package MyPack. This means that it
cannot be executed by itself. That is, you cannot use this command line:
java AccountBalance
AccountBalance must be qualified with its package name.
Example:
package pck1;
class Student
{
private int rollno;
private String name;
private String address;
public Student(int rno, String sname, String sadd)
{
rollno = rno; name = sname; address = sadd;
}
public void showDetails()
{
System.out.println("Roll No :: " + rollno);
System.out.println("Name :: " + name);
System.out.println("Address :: " + address);
}
}
public class DemoPackage
{
public static void main(String ar[])
{
Student st[]=new Student[2];
st[0] = new Student (1001,"Alice", "New York");
st[1] = new Student(1002,"BOb","Washington");
st[0].showDetails();
st[1].showDetails();
}
}
There are two ways to create package directory as follows:
23
1. Create the folder or directory at your choice location with the same name as package name.
After compilation of copy .class (byte code file) file into this folder.
2. Compile the file with following syntax.
javac -d <target location of package> sourceFile.java
The above syntax will create the package given in the sourceFile at the <target location of
pacakge> if it is not yet created. If package already exist then only the .class (byte code file)
will be stored to the package given in sourceFile.
Steps to compile the given example code:
Compile the code with the command on the command prompt. javac -d DemoPackage.java
1. The command will create the package at the current location with the name pck1, and
contains the file DemoPackage.class and Student.class
2. To run write the command given below java pckl.DemoPackage
Note: The DemoPackate.class is now stored in pck1 package. So that we've to use fully
qualified type name to run or access it.
Output:
Roll No :: 1001
Name :: Alice
Address :: New York
Roll No :: 1002
Name :: Bob
Address :: Washington
24
{
private int data=40;
private void msg()
{
System.out.println("Hello java");
}
}
public class Simple
{
public static void main(String args[])
{
A obj=new A();
System.out.println(obj.data);//Compile Time Error obj.msg();//Compile Time Error
}
}
2) Default Access Modifier
If you don't use any modifier, it is treated as default by default. The default modifier is
accessible only within package.
Example:
In this example, we have created two packages pack and mypack. We are accessing the A class
from outside its package, since A class is not public, so it cannot be accessed from outside the
package.
//save by A.java
package pack;
class A
{
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();//Compile Time Error obj.msg();//Compile Time Error
}
25
}
In the above example, the scope of class A and its method msg() is default so it cannot be
accessed from outside the package.
3) Protected Access Modifier
The protected access modifier is accessible within package and outside the package but through
inheritance only.
The protected access modifier can be applied on the data member, method and constructor. It
can't be applied on the class.
Example:
In this example, we have created the two packages pack and mypack. The A class of pack
package is public, so can be accessed from outside the package. But msg method of this
package is declared as protected, so it can be accessed from outside the class only through
inheritance.
//save by A.java
package pack;
public class A
{
protected void msg()
{
System.out.println("Hello");
}
}
//save by B.java
package mypack;
import pack.*;
class B extends A
{
public static void main(String args[])
{
B obj = new B();
obj.msg();
}
}
Output:
Hello
4) Public Access Modifier
The public access modifier is accessible everywhere. It has the widest scope among all other
modifiers.
Example:
26
//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();
}
}
Output:
Hello
import java.lang.*;
import java.util.*;
27
class MyDate extends Date {
}
Example:
interface printable
{
void print();
}
class A6 implements printable
{
public void print()
{
System.out.println("Hello");
28
}
public static void main(String args[])
{
A6 obj = new A6();
obj.print();
}
}
Output:
Hello
Example:
interface Drawable
{
void draw();
}
class Rectangle implements Drawable
{
public void draw()
{
System.out.println("drawing rectangle");
}
}
class Circle implements Drawable
{
public void draw()
{
System.out.println("drawing circle");
}
}
class TestInterface1
{
public static void main(String args[])
{
Drawable d=new Circle();//In real scenario, object is provided by method e.g. getDrawable()
d.draw();
}
}
Output:
29
drawing circle
Multiple inheritance in Java by interface
If a class implements multiple interfaces, or an interface extends multiple interfaces i.e. known
as multiple inheritance.
Example:
interface Printable
{
void print();
}
interface Showable
{
void show();
}
class A7 implements Printable, Showable
{
public void print()
{
System.out.println("Hello");
}
public void show()
{
System.out.println("Welcome");
}
public static void main(String args[])
{
A7 obj = new A7();
obj.print();
obj.show();
}
}
Output:
Hello Welcome
30
Interface inheritance
A class implements interface but one interface extends another interface .
Example:
interface Printable
{
void print();
}
interface Showable extends Printable
{
void show();
}
class TestInterface4 implements Showable
{
public void print()
{
System.out.println("Hello");
}
public void show()
{
System.out.println("Welcome");
}
public static void main(String args[])
{
TestInterface4 obj = new TestInterface4();
obj.print();
obj.show();
}
}
Output:
Hello Welcome
Nested Interface in Java
An interface can have another interface i.e. known as nested interface.
interface printable
{
void print();
interface MessagePrintable
{
void msg();
}
31
}
Key points to remember about interfaces:
1) We can’t instantiate an interface in java. That means we cannot create the object of an
interface
2) Interface provides full abstraction as none of its methods have body. On the other hand
abstract class provides partial abstraction as it can have abstract and concrete(methods with
body) methods both.
3) “implements” keyword is used by classes to implement an interface.
4) While providing implementation in class of any method of an interface, it needs to be
mentioned as public.
5) Class that implements any interface must implement all the methods of that interface, else
the class should be declared abstract.
6) Interface cannot be declared as private, protected or transient.
7) All the interface methods are by default abstract and public.
8) Variables declared in interface are public, static and final by default. interface Try
{
int a=10; public int a=10;
public static final int a=10; final int a=10;
static int a=0;
}
All of the above statements are identical.
9) Interface variables must be initialized at the time of declaration otherwise, compiler will
throw an error.
interface Try
{
int x;//Compile-time error
}
Above code will throw a compile time error as the value of the variable x is not initialized at
the time of declaration.
10) Inside any implementation class, you cannot change the variables declared in interface
because by default, they are public, static and final. Here we are implementing the interface
“Try” which has a variable x. When we tried to set the value for variable x we got compilation
error as the variable x is public static final by default and final variables can not be re-
initialized.
class Sample implements Try
{
public static void main(String args[])
{
x=20; //compile time error
32
}
}
11) An interface can extend any interface but cannot implement it. Class implements interface
and interface extends interface.
12) A class can implement any number of interfaces.
13) If there are two or more same methods in two interfaces and a class implements both
interfaces, implementation of the method once is enough.
interface A
{
public void aaa();
}
interface B
{
public void aaa();
}
class Central implements A,B
{
public void aaa()
{
//Any Code here
}
public static void main(String args[])
{
//Statements
}
}
14) A class cannot implement two interfaces that have methods with same name but different
return type.
interface A
{
public void aaa();
}
interface B
{
public int aaa();
}
class Central implements A,B
{
33
public void aaa() // error
{
}
public int aaa() // error
{
}
public static void main(String args[])
{
}
}
15) Variable names conflicts can be resolved by interface name. interface A
• Without bothering about the implementation part, we can achieve the security of
implementation
• In java, multiple inheritance is not allowed, however you can use interface to make use of it as
you can implement more than one interface.
Interface A
{
int x=10;
}
interface B
{
int x=100;
}
class Hello implements A,B
{
public static void Main(String args[])
{
System.out.println(x);
System.out.println(A.x);
System.out.println(B.x);
}
}
• Without bothering about the implementation part, we can achieve the security of implementation
• In java, multiple inheritance is not allowed, however you can use interface to make use of it as
you can implement more than one interface.
34
ABSTRACT CLASS INTERFACE
1) Abstract class can have abstract and non- Interface can have only abstract methods.
abstract methods.
2) Abstract class doesn't support multiple Interface supports multiple inheritance.
inheritance.
3) Abstract class can have final, non-final, Interface has only static and final variables.
static and non-static variables.
4) Abstract class can provide the Interface can't provide the implementation
implementation of interface. of abstract class.
5) The abstract keyword is used to declare The interface keyword is used to declare
abstract class. interface.
35