UNIT -II
INHERITANCE, PACKAGES AND
INTERFACES
Overloading Methods – Objects as Parameters –
Returning Objects –Static, Nested and Inner
Classes. Inheritance: Basics– Types of
Inheritance -Super keyword -Method Overriding
– Dynamic Method Dispatch –Abstract Classes –
final with Inheritance. Packages and Interfaces:
Packages – Packages and Member Access –
Importing Packages – Interfaces.
Overloading Methods
• If a class has multiple methods having same name but
different in parameters
• If we have to perform only one operation, having
same name of the methods increases the readability
of the program
Advantage of method overloading
• Method overloading increases the readability of the
program
Different ways to overload the method
• There are two ways to overload the method in java
– By changing number of arguments
– By changing the data type
class Sum
{
static int add(int a, int b)
{ return a+b;
}
static double add(double a, double b)
{ return a+b;
} }
class TestOverloading2
{
public static void main(String[] args)
{
System.out.println(Sum.add(17,13));
System.out.println(Sum.add(10.4,10.6));
} }
Some points to remember about method
overloading:
• Method overloading cannot be done by
changing the return type of methods
• The most important rule of method
overloading is that two overloaded methods
must have different parameters
• When an overloaded method is called, Java looks a
match between the arguments used to call the method
and the method’s parameters.
• match need not always be exact
• In some cases, Java’s automatic type conversions can
play a role in overload resolution.
// Automatic type conversions apply to overloading.
class OverloadDemo {
void test() {
System.out.println("No parameters");
}
// Overload test for two integer parameters.
void test(int a, int b) {
System.out.println("a and b: " + a + " " + b);
}
// overload test for a double parameter
void test(double a) {
System.out.println("Inside test(double) a: " + a);
}
}
class Overload {
public static void main(String args[]) {
OverloadDemo ob = new OverloadDemo();
int i = 88;
ob.test();
ob.test(10, 20);
ob.test(i); // this will invoke test(double)
ob.test(123.2); // this will invoke test(double)
}
}
Output:
No parameters
a and b: 10 20
Inside
test(double) a: 88
Inside
test(double) a:
123.2
Objects as Parameters
• A method can take an objects as a parameter
• pass an object as an argument to a method, the
mechanism that applies is called pass-by-reference
• Because copy of the reference contained in the variable
is transferred to the method, not a copy of the object
itself
• While creating a variable of a class type, we only create
a reference to an object
• when we pass this reference to a method, the parameter
that receives it will refer to the same object as that
referred to by the argument
// 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));
}
}
output:
ob1 == ob2: true
ob1 == ob3: false
Test ob1 = new Test(100, 22);
Test ob2 = new Test(100, 22);
Test ob3 = new Test(-1, -1);
boolean equals(Test o);
System.out.println("ob1 == ob2: "
+ ob1.equals(ob2));
System.out.println("ob1 == ob3: "
+ ob1.equals(ob3));
• One of the most common uses of object parameters
involves constructors
• want to construct a new object so that it is initially the
same as some existing object.
• To do define a constructor that takes an object of its class
as a parameter
• For example, Box allows one object to initialize another:
// Here, Box allows one object to initialize another.
class Box {
double width;
double height;
double depth;
// Notice this constructor. It takes an object of type Box.
Box(Box ob) { // pass object to constructor
width = ob.width;
height = ob.height;
depth = ob.depth; }
// constructor used when all dimensions specified
Box(double w, double h, double d) {
width = w;
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 OverloadCons2 {
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);
Box myclone = new Box(mybox1); // create copy of mybox1
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 cube is " + vol);
// get volume of clone
vol = myclone.volume();
System.out.println("Volume of clone is " + vol);
// Primitive types are passed by value
class Test {
void meth(int i, int j) {
i *= 2;
j /= 2;
} }
class CallByValue {
public static void main(String args[]) {
Test ob = new Test();
int a = 15, b = 20;
System.out.println("a and b before call: " +
a + " " + b);
ob.meth(a, b);
System.out.println("a and b after call: " +
a + " " + b); } }
output:
a and b before
call: 15 20
a and b after call:
15 20
// Objects are passed by reference.
class Test {
int a, b;
Test(int i, int j) {
a = i;
b = j;
}
// pass an object
void meth(Test o) {
o.a *= 2;
o.b /= 2;
}
}
class CallByRef {
public static void main(String args[]) {
Test ob = new Test(15, 20);
System.out.println("ob.a and ob.b before call: " +
ob.a + " " + ob.b);
ob.meth(ob);
System.out.println("ob.a and ob.b after call: " +
ob.a + " " + ob.b);
}
}
output:
ob.a and ob.b before call: 15 20
ob.a and ob.b after call: 30 10
Returning Objects
• A method can return any type of data, including class types
that create
• incrByTen( ) method returns an object in which the value of a
is ten greater than it is in the invoking object
// Returning an object
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);
}
}
Output:
ob1.a: 2
ob2.a: 12
ob2.a after second
increase: 22
Static, Nested and Inner Classes
• Java inner class or nested class is a class that is declared
inside the class or interface
• Use inner classes to logically group classes and interfaces
in one place to be more readable and maintainable
• It can access all the members of the outer class, including
private data members and methods
• Syntax of Inner class
class Java_Outer_class
{
//code
class Java_Inner_class{
//code
}
}
Advantage:
• It represent a particular type of relationship that is it can
access all the members (data members and methods) of
the outer class, including private
• It used to develop more readable and maintainable
code because it logically group classes and interfaces in
one place only
• Code Optimization: It requires less code to write
• An inner class is a part of a nested class.
• Non-static nested classes are known as inner classes
Types of Nested classes
• Two types of nested classes non-static and
static nested classes
• Non-static nested classes are also known as
inner classes
• Non-static nested class (inner class)
Member inner class
Anonymous inner class
Local inner class
• Static nested class
Member Inner class
• Non-static class created inside a class but outside a
method is called member inner class
• It is also known as a regular inner class
• It can be declared with access modifiers like public,
default, private, and protected
• Syntax:
class Outer{
//code
class Inner{
//code
}
}
TestMemberOuter1.java
class TestMemberOuter1{
private int data=30;
class Inner{
void msg(){System.out.println("data is "+data);}
}
public static void main(String args[]){
TestMemberOuter1 obj=new TestMemberOuter1();
TestMemberOuter1.Inner in=obj.new Inner();
in.msg();
}
}
• msg() method in the member inner class that is accessing the
private data member of the outer class
Output:
data is 30
Anonymous inner class
• a class that has no name is known as an anonymous
inner class in Java
• It should be used to override a method of class or
interface
• Java Anonymous inner class can be created in two
ways:
Class
Interface
import java.util.*;
// Class 1 Helper class
class Demo {
void show()
{
System.out.println("i am in show method of super class");
} }
// Class 2 Main class
class Flavor1Demo {
// An anonymous class with Demo as base class
static Demo d = new Demo() {
void show()
{
// Calling method show() via super keyword which refers to
parent class
super.show();
System.out.println("i am in Flavor1Demo class");
} };
// Main driver method
public static void main(String[] args)
{
// Calling show() method inside main() method
d.show();
}
}
Output:
i am in show method of super class
i am in Flavor1Demo class
• two classes Demo and Flavor1Demo
• demo act as a super-class and the anonymous class acts as a
subclass, both classes have a method show()
• In anonymous class show() method is overridden
Method Local inner classes
• Inner class can be declared within a method of an
outer class
• 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");
}
}
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
• Local inner class cannot be invoked from outside the
method
Static nested classes
• A static class is a class that is created inside a class
• cannot access non-static data members and methods
• can be accessed by outer class name
• can access static data members of the outer class,
including private
// outer class
class OuterClass
{
// static member
static int outer_x = 10;
// instance(non-static) member
int outer_y = 20;
// private member
private static int outer_private = 30;
// static nested class
static class StaticNestedClass
{
void display()
{
System.out.println("outer_x = " + outer_x);
System.out.println("outer_private = " + outer_private);
// compilation error: static nested class cannot
directly access non-static members
// System.out.println("outer_y = " + outer_y);
}
}
}
// Driver class
public class StaticNestedClassDemo
{
public static void main(String[] args)
{
// accessing a static nested class
OuterClass.StaticNestedClass nestedObject = new
OuterClass.StaticNestedClass();
nestedObject.display();
} }
Output:
outer_x = 10
outer_private = 30
INHERITANCE
• 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
• one object acquires all the properties and behaviors of
another object
• Inheritance represents the IS-A relationship, also known
as parent-child relationship
• It is process of deriving a new class from an existing
class
• A class that is inherited is called a super class and the
class that does the inheriting is called a subclass
• Syntax:
class Subclass-name extends Superclass-name
{
//methods and fields
}
• extends keyword indicates that we are creating a new
class that derives from existing class
• Note:
The constructors of the superclass are never inherited
by subclass
Advantages of Inheritance
Code reusability - public methods of base class can
be reused in derived classes
 Data hiding – private data of base class cannot be
altered by derived class
Overriding--With inheritance, we will be able to
override the methods of the base class in the derived
class (so runtime polymorphism can be achieved)
// Create a superclass.
class BaseClass
{
int a=10,b=20;
public void add()
{ System.out.println(“Sum:”+(a+b));
}
}
// Create a subclass by extending class BaseClass.
public class Main extends BaseClass
{
public void sub()
{
System.out.println(“Difference:”+(a-b));
}
public static void main(String[] args) {
Main obj=new Main();
/*The subclass has access to all public members of its
superclass*/
obj.add();
obj.sub();
} }
• Main is the subclass and BaseClass is the superclass
• Main object can access the field of own class as well as
of BaseClass class i.e. code reusability
Output:
Sum:30
Difference:-10
Types of inheritance
Single Inheritance :
• subclass inherit the features of one superclass
class Shape{
int a=10,b=20;
}
class Rectangle extends Shape{
public void rectArea(){
System.out.println(“Rectangle Area:”+(a*b));
} }
public class Main
{
public static void main(String[] args) {
Rectangle obj=new Rectangle();
obj.rectArea();
} }
Output:
Rectangle Area:200
Multilevel Inheritance:
• derived class will be inheriting a base class and as well
as the derived class also act as the base class to other
class
• a derived class in turn acts as a base class for another
class
class Numbers{
int a=10,b=20;
}
class Add2 extends Numbers{
int c=30;
public void sum2(){
System.out.println(“Sum of 2 nos.:”+(a+b));
}
}
Class A
Class B
Class C
class Add3 extends Add2{
public void sum3(){
System.out.println(“Sum of 3 nos.:”+(a+b+c));
}
}
public class Main
{
public static void main(String[] args)
{
Add3 obj=new Add3();
obj.sum2();
obj.sum3();
}
}
Output:
Sum of 2 nos.:30
Sum of 3 nos.:60
Hierarchical Inheritance
• one class serves as a super class (base class) for more than one sub
class
• one class(class A) is inherited by many sub classes(class B & C)
class Shape{
int a=10,b=20;
}
class Rectangle extends Shape{
public void rectArea(){
System.out.println(“Rectangle Area:”+(a*b));
}
}
class Triangle extends Shape{
public void triArea(){
System.out.println(“Triangle Area:”+(0.5*a*b));
}
}
Class A
Class C
Class B
public class Main
{
public static void main(String[] args) {
Rectangle obj=new Rectangle();
obj.rectArea();
Triangle obj1=new Triangle();
obj1.triArea();
}
}
Output:
Rectangle Area:200
Triangle Area:100.0
Multiple inheritance
• Java does not allow multiple inheritance:
• Direct implementation of multiple inheritance is not allowed in
Java. But it is achievable using Interfaces
Hybrid Inheritance:
• combination of both Single and Multiple Inheritance
• Hybrid inheritance is also not directly supported in Java only
through interface
Class A
Class C
Class B
Class C
Class B
Class D
Class A
PACKAGES
• is a group of similar types of classes, interfaces and sub-
packages.
• Package in java can be categorized in two form,
 built-in package
user-defined package.
• There are many built-in packages
– 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>;
• 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
package pkg1[.pkg2[.pkg3]];
• For example, a package declared as
package java.awt.image;
• needs to be stored in javaawtimage in a Windows
environment
• We cannot rename a package without renaming the
directory in which the classes are stored.
Simple example
//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
} }
• compile java package
• syntax
javac -d directory javafilename
• example
javac -d . Simple.java
• The -d switch specifies the destination where to put the generated
class file.
• want to keep the package within the same directory, you can use .
(dot).
• run java package program
• need to use fully qualified name e.g. mypack.Simple to run
the class.
• To Compile:
javac -d . Simple.java
• To Run:
java mypack.Simple
• Output:
Welcome to package
• The -d is a switch that tells the compiler where to put the class
file i.e. it represents destination
• The . represents the current folder.
To access package from another package
• There are three ways to access the package from
outside the package.
1. import package.*;
2. import package.classname;
3. fully qualified name.
1) Using packagename.*
• If you use package.* then all the classes and
interfaces of this package will be accessible but not
subpackages.
• The import keyword is used to make the classes and
interface of another package accessible to the current
package.
//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
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();
} }
Output:Hello
3) Using fully qualified name
• use fully qualified name then only declared class of this
package will be accessible - no need to import.
• need to use fully qualified name every time when you are
accessing the class or interface
/save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");} }
//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();
}
}
Output:Hello
Access Control
• The rules for inherited Variables & Methods:
• Variables declared public or protected in a super class are
inheritable in subclasses
• Variables or Methods declared private in a super class are not
inherited at all
• Methods declared public in a super class also must be public in
all subclasses
• Methods declared protected in a super class must either be
protected or public in subclasses; they cannot be private
Example:
// Create a superclass
class A{
int x; // default specifier
private int y; // private to A
public void set_xy(int a,int b){
x=a;
y=b;
}
}
// A’s y is not accessible here.
class B extends A{
public void add(){
System.out.println(“Sum:”+(x+y)); //Error: y has private access
in A – not inheritable
}
}
class Main{
public static void main(String args[]){
B obj=new B();
obj.set_xy(10,20);
obj.add();
} }
Using Super
• super keyword refers to immediate parent class
• Object create the instance of subclass, an instance of
parent class is created implicitly which is referred by
super reference variable
• used to refer immediate parent class instance variable
when both parent and child class have same member
name
• used to invoke immediate parent class method when
child class has overridden that method
• super() can be used to invoke immediate parent class
constructor
Use of super with variables:
• When both parent and child class have member with
same name, use super keyword to access member of
parent class
class SuperCls
{
int x = 20;
}
/* sub class SubCls extending SuperCls */
class SubCls extends SuperCls
{
int x = 80;
void display()
{
System.out.println(“Super Class x: “ + super.x); //print x
of super class
System.out.println(“Sub Class x: “ + x); //print x of
subclass
}
}
/* Driver program to test */
class Main
{
public static void main(String[] args)
{
SubCls obj = new SubCls();
obj.display();
}
}
Output:
Super Class x: 20
Sub Class x: 80
Use of super with methods:
• super keyword also used to invoke parent class method
• It should be used if subclass contains the same method as
parent class (Method Overriding)
class SuperCls
{
int x = 20;
void display(){ //display() in super class
System.out.println(“Super Class x: “ + x);
} }
/* sub class SubCls extending SuperCls */
class SubCls extends SuperCls
{
int x = 80;
void display() //display() in sub class – method overriding
{
System.out.println(“Sub Class x: “ + x);
super.display(); // invoke super class display()
} }
/* Driver program to test */
class Main
{
public static void main(String[] args)
{
SubCls obj = new SubCls();
obj.display();
}
}
Output:
Sub Class x: 80
Super Class x: 20
Use of super with constructors:
• The super keyword can also be used to invoke the
parent class constructor
• Syntax:
super();
• first statement executed inside a subclass constructor
• invoke a super() statement from within a subclass
constructor, invoking the immediate super class
constructor
• Example:
class SuperCls
{
SuperCls(){
System.out.println(“In Super Constructor”);
}
}
/* sub class SubCls extending SuperCls */
class SubCls extends SuperCls
{
SubCls(){
super();
System.out.println(“In Sub Constructor”);
}
}
/* Driver program to test */
class Main
{
public static void main(String[] args)
{
SubCls obj = new SubCls();
}
}
Output:
In Super Constructor
In Sub Constructor
Method Overriding
• In a class hierarchy, when a method in subclass
has same name and type signature as a method
in its super class, then method in subclass is
said to override the method in super class
• When an overridden method is called from
within a subclass, it will always refer to the
version of that method defined by the subclass
• version of method defined by the super class
will be hidden
// Method overriding
class A {
int i, j;
A(int a, int b) {
i = a;
j = b;
}
// display i and j
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;
}
// display k – this overrides show() in A
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
}
}
output
k: 3
class B extends A {
int k;
B(int a, int b, int c) {
super(a, b);
k = c;
}
void show() {
super.show(); // this calls A's show()
System.out.println("k: " + k);
}
}
• to access the super class version of an overridden
method by using super
Output:
i and j: 1 2
k: 3
Dynamic Method Dispatch
• A mechanism to resolve overridden method call at run time
instead of compile time
• It is based on the concept of up-casting
• A super class reference variable can refer subclass object
• it is the type of the object being referred to
• not the type of the reference variable
• Super class contains a method that is overridden by a
subclass
• overridden method is called through a super class reference
• Java determines which version of that method to execute
based upon the type of the object being referred to at the
time the call occurs
• this determination is made at run time
class A {
void callme() {
System.out.println("Inside A's callme method");
}
}
class B extends A {
// override callme()
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
}
}
Output:
Inside A’s callme
method
Inside B’s callme
method
Inside C’s callme
method
ABSTRACT CLASS
• A class that is declared with abstract keyword, is known as
abstract class
• It can have abstract and non-abstract methods (method with
body)
• Abstraction is a process of hiding the implementation details and
showing only functionality to user
• Abstraction focus on what the object does instead of how it does
it
• It needs to be extended and its method implemented
• Syntax:
abstract class classname
{
}
Abstract method
• A method that is declared as abstract and does not have
implementation
• The method body will be defined by its subclass
• Abstract method can never be final and static
• Any class that extends an abstract class must implement all abstract
methods declared by the super class
• Syntax:
abstract returntype functionname (); //No definition
• Syntax for abstract class and method:
modifier abstract class className
{
//declare fields
//declare methods
abstract dataType methodName();
}
modifier class childClass extends className
{
dataType methodName()
{
}
}
Rules
1. Abstract classes are not Interfaces.
2. may have concrete (complete) methods
3. may or may not have an abstract method. But if any class has one or
more abstract methods, it must be compulsorily labeled abstract
4. can have Constructors, Member variables and Normal methods
5. For design purpose, a class can be declared abstract even if it does
not contain any abstract methods
6. Reference of an abstract class can point to objects of its sub-classes
thereby achieving run-time polymorphism Ex: Shape obj = new
Rectangle();
7. A class derived from the abstract class must implement all those
methods that are declared as abstract in the parent class
8. If a child does not implement all the abstract methods of abstract
parent class, then the child class must need to be declared abstract as
well.
//abstract parent class
abstract class Animal
{
//abstract method
public abstract void sound();
}
//Lion class extends Animal class
public class Lion extends Animal
{
public void sound()
{
System.out.println(“Roars”);
}
public static void main(String args[])
{
Animal obj = new Lion();
obj.sound();
}
Output:
Roars
In the above code, Animal is an
abstract class and Lion is a
concrete class.
abstract class Bank
{
abstract int getRateOfInterest();
}
class SBI extends Bank
{
int getRateOfInterest()
{
return 7;
}
}
class PNB extends Bank
{
int getRateOfInterest()
{
return 8;
}
}
public class TestBank
{
public static void main(String args[])
{
Bank b=new SBI();//if object is PNB, method of
PNB will be invoked
int interest=b.getRateOfInterest();
System.out.println(“Rate of Interest is:
“+interest+” %”);
b=new PNB();
System.out.println(“Rate of Interest is:
“+b.getRateOfInterest()+” %”);
}
}
Output:
Rate of Interest is: 7 %
Rate of Interest is: 8 %
Final Methods and Classes
• The final keyword in java is used to restrict the user.
• The java final keyword can be applied to:
Variable- To prevent constant variables
method - To prevent method overriding
class- To prevent inheritance
• Java final variable
• final keyword can be applied with the variables
• final variable that have no value it is called blank final variable
or uninitialized final variable.
• It can be initialized in the constructor only.
• blank final variable can be static also which will be initialized
in the static block only.
public class Vehicle
{
final int speedlimit=60;//final variable
void run()
{
speedlimit=400;
}
public static void main(String args[])
{
Vehicle obj=new Vehicle();
obj.run();
}
}
• A final variable speed limit is defined within a class Vehicle.
• try to change the value of this variable, we get an error
• value of final variable cannot be changed, once a value is assigned
to it.
Output:
/Vehicle.java:6: error: cannot
assign a value to final variable
speedlimit
speedlimit=400;
^
1 error
Blank final variable
• A final variable that is not initialized at the time of declaration
is known as blank final variable.
• We must initialize the blank final variable in constructor of the
class otherwise it will throw a compilation error
public class Vehicle
{
final int speedlimit; //blank final variable
void run()
{
}
public static void main(String args[])
{
Vehicle obj=new Vehicle();
obj.run();
}
}
Output:
/Vehicle.java:3: error: variable
speedlimit not initialized in the
default constructor
final int speedlimit; //blank final
variable
^
1 error
Java Final Method
• method with the final keyword is called a final method and it
cannot be overridden in the subclass.
• final methods are inherited but they cannot be overridden
class Bike{
final void run(){System.out.println("running");}
}
class Honda extends Bike{
void run(){System.out.println("running safely with 100kmph");
}
public static void main(String args[]){
Honda honda= new Honda();
honda.run();
}
}
Output:Compile
Time Error
class XYZ
{
final void demo()
{
System.out.println(“XYZ Class Method”);
}
}
public class ABC extends XYZ
{
public static void main(String args[])
{
ABC obj= new ABC();
obj.demo();
}
}
Output:
XYZ Class Method
Java Final Class
• Final class is a class that cannot be extended i.e. it cannot be
inherited.
• A final class can be a subclass but not a super class.
• Declaring a class as final implicitly declares all of its methods as
final
• Several classes in Java are final e.g. String, Integer, and other
wrapper classes.
• The final keyword can be placed either before or after the access
specifier
• Syntax:
final public class A
{ OR
//code
}
public final class A
{
//code
}
final class XYZ
{
}
public class ABC extends XYZ
{
void demo()
{
System.out.println(“My Method”);
}
public static void main(String args[])
{
ABC obj= new ABC();
obj.demo();
}
}
Output:
/ABC.java:5: error: cannot inherit
from final XYZ
public class ABC extends XYZ
^
1 error
INTERFACES
• An interface in java is a blueprint of a class
• An interface is a reference type in Java
• similar to class
• collection of abstract methods
• may also contain constants, default methods, static methods, and
nested types.
• Method bodies exist only for default methods and static methods
An interface is similar to a class in the following ways:
• interface can contain any number of methods
• interface is written in a file with a .java extension, with the name
of the interface matching the name of the file
• byte code of an interface appears in a .class file
• Interfaces appear in packages, and their corresponding byte code
file must be in a directory structure that matches the package name
Uses of interface:
• java does not support multiple inheritance in case of
class, it can be achieved by using interface
• It is also used to achieve loose coupling
• Interfaces are used to implement abstraction
Defining an Interface
• An interface is defined much like a class
Syntax:
accessspecifier interface interfacename
{
return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
type final-varname1 = value;
type final-varname2 = value;
// ...
return-type method-nameN(parameter-list);
type final-varnameN = value;
}
/* File name : Animal.java */
interface Animal {
public void eat();
public void travel();
}
Implementing an Interface
• Once an interface has been defined, one or more classes
can implement that interface
• To implement an interface, the ‘implements’ clause
included in a class definition and then methods defined
by the interface are created.
Syntax:
class classname [extends superclass] [implements interface
[,interface...]]
{
// class-body
}
Rules
• A class can implement more than one interface at a time.
• A class can extend only one class, but can implement many
interfaces.
• An interface can extend another interface, in a similar way as a
class can extend another class
/* File name : Mammal.java */
public class Mammal implements Animal
{
public void eat()
{
System.out.println(“Mammal eats”);
}
public void travel()
{
System.out.println(“Mammal travels”);
}
public int noOfLegs()
{
return 0;
}
public static void main(String args[])
{
Mammal m = new Mammal();
m.eat();
m.travel();
}
}
Output:
Mammal eats
Mammal travels
import java.io.*;
// A simple interface
interface Sample
{
final String name = “Shree”;
void display();
}
// A class that implements interface.
public class testClass implements
Sample
{
public void display()
{
System.out.println(“Welcome”);
}
public static void main
(String[] args)
{
testClass t = new testClass();
t.display();
System.out.println(name);
}
}
Output:
Welcome
Shree
Nested Interface
• An interface can be declared as a member of a class or another
interface
• Such an interface is called a member interface or a nested
interface
• A nested interface can be declared as public, private, or
protected
interface MyInterfaceA
{
void display();
interface MyInterfaceB
{
void myMethod();
}
}
public class NestedInterfaceDemo implements
MyInterfaceA.MyInterfaceB
{
public void myMethod()
{
System.out.println(“Nested interface method”);
}
public static void main(String args[])
{
MyInterfaceA.MyInterfaceB obj= new NestedInterfaceDemo();
obj.myMethod();
}
}
Output:
Nested interface method
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
Interface inheritance
Aspect for
comparison
Class Interface
Basic A class is instantiated to create
objects
An interface can never be instantiated
as the methods are unable to perform
any action on invoking
Keyword class Interface
Access
specifier
The members of a class can be
private, public or protected.
The members of an interface are
always public
Methods The methods of a class are defined
to perform a specific action
The methods in an interface are purely
abstract
inheritance A class can implement any number
of interfaces and can extend
only one class.
An interface can extend multiple
interfaces but cannot implement
any interface.
Inheritance
keyword
extends Implements
Constructor A class can have constructors to
initialize the variables.
An interface can never have a
constructor as there is hardly any
variable to initialize.
ABSTRACT CLASS INTERFACE
1) Abstract class can have abstract and non-
abstract methods
Interface can have only abstract methods.
2) Abstract class doesn't support multiple
inheritance.
Interface supports multiple inheritance.
3) Abstract class can have final, non-final,
static and non-static variables
Interface has only static and final variables
4) Abstract class can provide the
implementation of interface.
Interface can't provide the implementation of
abstract class.
5) The abstract keyword is used to declare
abstract class
The interface keyword is used to declare
interface.
6) An abstract class can extend another Java
class and implement multiple Java interfaces.
An interface can extend another Java
interface only.
7) An abstract class can be extended using
keyword extends.
An interface class can be implemented using
keyword implements
8) A Java abstract class can have class
members like private, protected, etc.
Members of a Java interface are public by
default.

UNIT_-II_2021R.pptx

  • 1.
  • 2.
    Overloading Methods –Objects as Parameters – Returning Objects –Static, Nested and Inner Classes. Inheritance: Basics– Types of Inheritance -Super keyword -Method Overriding – Dynamic Method Dispatch –Abstract Classes – final with Inheritance. Packages and Interfaces: Packages – Packages and Member Access – Importing Packages – Interfaces.
  • 3.
    Overloading Methods • Ifa class has multiple methods having same name but different in parameters • If we have to perform only one operation, having same name of the methods increases the readability of the program Advantage of method overloading • Method overloading increases the readability of the program Different ways to overload the method • There are two ways to overload the method in java – By changing number of arguments – By changing the data type
  • 4.
    class Sum { static intadd(int a, int b) { return a+b; } static double add(double a, double b) { return a+b; } } class TestOverloading2 { public static void main(String[] args) { System.out.println(Sum.add(17,13)); System.out.println(Sum.add(10.4,10.6)); } }
  • 5.
    Some points toremember about method overloading: • Method overloading cannot be done by changing the return type of methods • The most important rule of method overloading is that two overloaded methods must have different parameters
  • 6.
    • When anoverloaded method is called, Java looks a match between the arguments used to call the method and the method’s parameters. • match need not always be exact • In some cases, Java’s automatic type conversions can play a role in overload resolution. // Automatic type conversions apply to overloading. class OverloadDemo { void test() { System.out.println("No parameters"); } // Overload test for two integer parameters. void test(int a, int b) { System.out.println("a and b: " + a + " " + b); }
  • 7.
    // overload testfor a double parameter void test(double a) { System.out.println("Inside test(double) a: " + a); } } class Overload { public static void main(String args[]) { OverloadDemo ob = new OverloadDemo(); int i = 88; ob.test(); ob.test(10, 20); ob.test(i); // this will invoke test(double) ob.test(123.2); // this will invoke test(double) } } Output: No parameters a and b: 10 20 Inside test(double) a: 88 Inside test(double) a: 123.2
  • 8.
    Objects as Parameters •A method can take an objects as a parameter • pass an object as an argument to a method, the mechanism that applies is called pass-by-reference • Because copy of the reference contained in the variable is transferred to the method, not a copy of the object itself • While creating a variable of a class type, we only create a reference to an object • when we pass this reference to a method, the parameter that receives it will refer to the same object as that referred to by the argument
  • 9.
    // Objects maybe 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)); } } output: ob1 == ob2: true ob1 == ob3: false
  • 10.
    Test ob1 =new Test(100, 22); Test ob2 = new Test(100, 22); Test ob3 = new Test(-1, -1); boolean equals(Test o);
  • 11.
    System.out.println("ob1 == ob2:" + ob1.equals(ob2)); System.out.println("ob1 == ob3: " + ob1.equals(ob3));
  • 12.
    • One ofthe most common uses of object parameters involves constructors • want to construct a new object so that it is initially the same as some existing object. • To do define a constructor that takes an object of its class as a parameter • For example, Box allows one object to initialize another: // Here, Box allows one object to initialize another. class Box { double width; double height; double depth;
  • 13.
    // Notice thisconstructor. It takes an object of type Box. Box(Box ob) { // pass object to constructor width = ob.width; height = ob.height; depth = ob.depth; } // constructor used when all dimensions specified Box(double w, double h, double d) { width = w; height = h; depth = d; } // constructor used when no dimensions specified Box() { width = -1; // use -1 to indicate height = -1; // an uninitialized depth = -1; // box }
  • 14.
    // constructor usedwhen cube is created Box(double len) { width = height = depth = len; } // compute and return volume double volume() { return width * height * depth; } } class OverloadCons2 { public static void main(String args[]) { // create boxes using the various constructors Box mybox1 = new Box(10, 20, 15); Box mybox2 = new Box();
  • 15.
    Box mycube =new Box(7); Box myclone = new Box(mybox1); // create copy of mybox1 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 cube is " + vol); // get volume of clone vol = myclone.volume(); System.out.println("Volume of clone is " + vol);
  • 16.
    // Primitive typesare passed by value class Test { void meth(int i, int j) { i *= 2; j /= 2; } } class CallByValue { public static void main(String args[]) { Test ob = new Test(); int a = 15, b = 20; System.out.println("a and b before call: " + a + " " + b); ob.meth(a, b); System.out.println("a and b after call: " + a + " " + b); } } output: a and b before call: 15 20 a and b after call: 15 20
  • 17.
    // Objects arepassed by reference. class Test { int a, b; Test(int i, int j) { a = i; b = j; } // pass an object void meth(Test o) { o.a *= 2; o.b /= 2; } }
  • 18.
    class CallByRef { publicstatic void main(String args[]) { Test ob = new Test(15, 20); System.out.println("ob.a and ob.b before call: " + ob.a + " " + ob.b); ob.meth(ob); System.out.println("ob.a and ob.b after call: " + ob.a + " " + ob.b); } } output: ob.a and ob.b before call: 15 20 ob.a and ob.b after call: 30 10
  • 19.
    Returning Objects • Amethod can return any type of data, including class types that create • incrByTen( ) method returns an object in which the value of a is ten greater than it is in the invoking object // Returning an object class Test { int a; Test(int i) { a = i; } Test incrByTen() { Test temp = new Test(a+10); return temp; } }
  • 20.
    class RetOb { publicstatic 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); } } Output: ob1.a: 2 ob2.a: 12 ob2.a after second increase: 22
  • 21.
    Static, Nested andInner Classes • Java inner class or nested class is a class that is declared inside the class or interface • Use inner classes to logically group classes and interfaces in one place to be more readable and maintainable • It can access all the members of the outer class, including private data members and methods • Syntax of Inner class class Java_Outer_class { //code class Java_Inner_class{ //code } }
  • 22.
    Advantage: • It representa particular type of relationship that is it can access all the members (data members and methods) of the outer class, including private • It used to develop more readable and maintainable code because it logically group classes and interfaces in one place only • Code Optimization: It requires less code to write • An inner class is a part of a nested class. • Non-static nested classes are known as inner classes
  • 23.
    Types of Nestedclasses • Two types of nested classes non-static and static nested classes • Non-static nested classes are also known as inner classes • Non-static nested class (inner class) Member inner class Anonymous inner class Local inner class • Static nested class
  • 24.
    Member Inner class •Non-static class created inside a class but outside a method is called member inner class • It is also known as a regular inner class • It can be declared with access modifiers like public, default, private, and protected • Syntax: class Outer{ //code class Inner{ //code } }
  • 25.
    TestMemberOuter1.java class TestMemberOuter1{ private intdata=30; class Inner{ void msg(){System.out.println("data is "+data);} } public static void main(String args[]){ TestMemberOuter1 obj=new TestMemberOuter1(); TestMemberOuter1.Inner in=obj.new Inner(); in.msg(); } } • msg() method in the member inner class that is accessing the private data member of the outer class Output: data is 30
  • 26.
    Anonymous inner class •a class that has no name is known as an anonymous inner class in Java • It should be used to override a method of class or interface • Java Anonymous inner class can be created in two ways: Class Interface
  • 27.
    import java.util.*; // Class1 Helper class class Demo { void show() { System.out.println("i am in show method of super class"); } } // Class 2 Main class class Flavor1Demo { // An anonymous class with Demo as base class static Demo d = new Demo() { void show() { // Calling method show() via super keyword which refers to parent class super.show(); System.out.println("i am in Flavor1Demo class"); } };
  • 28.
    // Main drivermethod public static void main(String[] args) { // Calling show() method inside main() method d.show(); } } Output: i am in show method of super class i am in Flavor1Demo class • two classes Demo and Flavor1Demo • demo act as a super-class and the anonymous class acts as a subclass, both classes have a method show() • In anonymous class show() method is overridden
  • 29.
    Method Local innerclasses • Inner class can be declared within a method of an outer class • 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"); } } Inner y = new Inner(); y.innerMethod(); }
  • 30.
    class MethodDemo { publicstatic void main(String[] args) { Outer x = new Outer(); x.outerMethod(); } } Output: Inside outerMethod Inside innerMethod • Local inner class cannot be invoked from outside the method
  • 31.
    Static nested classes •A static class is a class that is created inside a class • cannot access non-static data members and methods • can be accessed by outer class name • can access static data members of the outer class, including private // outer class class OuterClass { // static member static int outer_x = 10; // instance(non-static) member int outer_y = 20; // private member private static int outer_private = 30;
  • 32.
    // static nestedclass static class StaticNestedClass { void display() { System.out.println("outer_x = " + outer_x); System.out.println("outer_private = " + outer_private); // compilation error: static nested class cannot directly access non-static members // System.out.println("outer_y = " + outer_y); } } }
  • 33.
    // Driver class publicclass StaticNestedClassDemo { public static void main(String[] args) { // accessing a static nested class OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass(); nestedObject.display(); } } Output: outer_x = 10 outer_private = 30
  • 34.
    INHERITANCE • defined asthe 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 • one object acquires all the properties and behaviors of another object • Inheritance represents the IS-A relationship, also known as parent-child relationship • It is process of deriving a new class from an existing class • A class that is inherited is called a super class and the class that does the inheriting is called a subclass
  • 35.
    • Syntax: class Subclass-nameextends Superclass-name { //methods and fields } • extends keyword indicates that we are creating a new class that derives from existing class • Note: The constructors of the superclass are never inherited by subclass
  • 36.
    Advantages of Inheritance Codereusability - public methods of base class can be reused in derived classes  Data hiding – private data of base class cannot be altered by derived class Overriding--With inheritance, we will be able to override the methods of the base class in the derived class (so runtime polymorphism can be achieved)
  • 37.
    // Create asuperclass. class BaseClass { int a=10,b=20; public void add() { System.out.println(“Sum:”+(a+b)); } } // Create a subclass by extending class BaseClass. public class Main extends BaseClass {
  • 38.
    public void sub() { System.out.println(“Difference:”+(a-b)); } publicstatic void main(String[] args) { Main obj=new Main(); /*The subclass has access to all public members of its superclass*/ obj.add(); obj.sub(); } } • Main is the subclass and BaseClass is the superclass • Main object can access the field of own class as well as of BaseClass class i.e. code reusability Output: Sum:30 Difference:-10
  • 39.
    Types of inheritance SingleInheritance : • subclass inherit the features of one superclass class Shape{ int a=10,b=20; } class Rectangle extends Shape{ public void rectArea(){ System.out.println(“Rectangle Area:”+(a*b)); } } public class Main { public static void main(String[] args) { Rectangle obj=new Rectangle(); obj.rectArea(); } } Output: Rectangle Area:200
  • 40.
    Multilevel Inheritance: • derivedclass will be inheriting a base class and as well as the derived class also act as the base class to other class • a derived class in turn acts as a base class for another class class Numbers{ int a=10,b=20; } class Add2 extends Numbers{ int c=30; public void sum2(){ System.out.println(“Sum of 2 nos.:”+(a+b)); } } Class A Class B Class C
  • 41.
    class Add3 extendsAdd2{ public void sum3(){ System.out.println(“Sum of 3 nos.:”+(a+b+c)); } } public class Main { public static void main(String[] args) { Add3 obj=new Add3(); obj.sum2(); obj.sum3(); } } Output: Sum of 2 nos.:30 Sum of 3 nos.:60
  • 42.
    Hierarchical Inheritance • oneclass serves as a super class (base class) for more than one sub class • one class(class A) is inherited by many sub classes(class B & C) class Shape{ int a=10,b=20; } class Rectangle extends Shape{ public void rectArea(){ System.out.println(“Rectangle Area:”+(a*b)); } } class Triangle extends Shape{ public void triArea(){ System.out.println(“Triangle Area:”+(0.5*a*b)); } } Class A Class C Class B
  • 43.
    public class Main { publicstatic void main(String[] args) { Rectangle obj=new Rectangle(); obj.rectArea(); Triangle obj1=new Triangle(); obj1.triArea(); } } Output: Rectangle Area:200 Triangle Area:100.0
  • 44.
    Multiple inheritance • Javadoes not allow multiple inheritance: • Direct implementation of multiple inheritance is not allowed in Java. But it is achievable using Interfaces Hybrid Inheritance: • combination of both Single and Multiple Inheritance • Hybrid inheritance is also not directly supported in Java only through interface Class A Class C Class B Class C Class B Class D Class A
  • 45.
    PACKAGES • is agroup of similar types of classes, interfaces and sub- packages. • Package in java can be categorized in two form,  built-in package user-defined package. • There are many built-in packages – 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
  • 46.
    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>; • For example, the following statement creates a package called MyPackage package MyPackage;
  • 47.
    • Java usesfile 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 package pkg1[.pkg2[.pkg3]]; • For example, a package declared as package java.awt.image; • needs to be stored in javaawtimage in a Windows environment • We cannot rename a package without renaming the directory in which the classes are stored.
  • 48.
    Simple example //save asSimple.java package mypack; public class Simple{ public static void main(String args[]){ System.out.println("Welcome to package"); } } • compile java package • syntax javac -d directory javafilename • example javac -d . Simple.java • The -d switch specifies the destination where to put the generated class file. • want to keep the package within the same directory, you can use . (dot).
  • 49.
    • run javapackage program • need to use fully qualified name e.g. mypack.Simple to run the class. • To Compile: javac -d . Simple.java • To Run: java mypack.Simple • Output: Welcome to package • The -d is a switch that tells the compiler where to put the class file i.e. it represents destination • The . represents the current folder.
  • 50.
    To access packagefrom another package • There are three ways to access the package from outside the package. 1. import package.*; 2. import package.classname; 3. fully qualified name. 1) Using packagename.* • If you use package.* then all the classes and interfaces of this package will be accessible but not subpackages. • The import keyword is used to make the classes and interface of another package accessible to the current package.
  • 51.
    //save by A.java packagepack; 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
  • 52.
    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(); } } Output:Hello
  • 53.
    3) Using fullyqualified name • use fully qualified name then only declared class of this package will be accessible - no need to import. • need to use fully qualified name every time when you are accessing the class or interface /save by A.java package pack; public class A{ public void msg(){System.out.println("Hello");} } //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(); } } Output:Hello
  • 54.
    Access Control • Therules for inherited Variables & Methods: • Variables declared public or protected in a super class are inheritable in subclasses • Variables or Methods declared private in a super class are not inherited at all • Methods declared public in a super class also must be public in all subclasses • Methods declared protected in a super class must either be protected or public in subclasses; they cannot be private Example: // Create a superclass class A{ int x; // default specifier private int y; // private to A
  • 55.
    public void set_xy(inta,int b){ x=a; y=b; } } // A’s y is not accessible here. class B extends A{ public void add(){ System.out.println(“Sum:”+(x+y)); //Error: y has private access in A – not inheritable } } class Main{ public static void main(String args[]){ B obj=new B(); obj.set_xy(10,20); obj.add(); } }
  • 56.
    Using Super • superkeyword refers to immediate parent class • Object create the instance of subclass, an instance of parent class is created implicitly which is referred by super reference variable • used to refer immediate parent class instance variable when both parent and child class have same member name • used to invoke immediate parent class method when child class has overridden that method • super() can be used to invoke immediate parent class constructor Use of super with variables: • When both parent and child class have member with same name, use super keyword to access member of parent class
  • 57.
    class SuperCls { int x= 20; } /* sub class SubCls extending SuperCls */ class SubCls extends SuperCls { int x = 80; void display() { System.out.println(“Super Class x: “ + super.x); //print x of super class System.out.println(“Sub Class x: “ + x); //print x of subclass } }
  • 58.
    /* Driver programto test */ class Main { public static void main(String[] args) { SubCls obj = new SubCls(); obj.display(); } } Output: Super Class x: 20 Sub Class x: 80
  • 59.
    Use of superwith methods: • super keyword also used to invoke parent class method • It should be used if subclass contains the same method as parent class (Method Overriding) class SuperCls { int x = 20; void display(){ //display() in super class System.out.println(“Super Class x: “ + x); } } /* sub class SubCls extending SuperCls */ class SubCls extends SuperCls { int x = 80;
  • 60.
    void display() //display()in sub class – method overriding { System.out.println(“Sub Class x: “ + x); super.display(); // invoke super class display() } } /* Driver program to test */ class Main { public static void main(String[] args) { SubCls obj = new SubCls(); obj.display(); } } Output: Sub Class x: 80 Super Class x: 20
  • 61.
    Use of superwith constructors: • The super keyword can also be used to invoke the parent class constructor • Syntax: super(); • first statement executed inside a subclass constructor • invoke a super() statement from within a subclass constructor, invoking the immediate super class constructor • Example: class SuperCls { SuperCls(){ System.out.println(“In Super Constructor”); } }
  • 62.
    /* sub classSubCls extending SuperCls */ class SubCls extends SuperCls { SubCls(){ super(); System.out.println(“In Sub Constructor”); } } /* Driver program to test */ class Main { public static void main(String[] args) { SubCls obj = new SubCls(); } } Output: In Super Constructor In Sub Constructor
  • 63.
    Method Overriding • Ina class hierarchy, when a method in subclass has same name and type signature as a method in its super class, then method in subclass is said to override the method in super class • When an overridden method is called from within a subclass, it will always refer to the version of that method defined by the subclass • version of method defined by the super class will be hidden
  • 64.
    // Method overriding classA { int i, j; A(int a, int b) { i = a; j = b; } // display i and j void show() { System.out.println("i and j: " + i + " " + j); } } class B extends A { int k;
  • 65.
    B(int a, intb, int c) { super(a, b); k = c; } // display k – this overrides show() in A 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 } } output k: 3
  • 66.
    class B extendsA { int k; B(int a, int b, int c) { super(a, b); k = c; } void show() { super.show(); // this calls A's show() System.out.println("k: " + k); } } • to access the super class version of an overridden method by using super Output: i and j: 1 2 k: 3
  • 67.
    Dynamic Method Dispatch •A mechanism to resolve overridden method call at run time instead of compile time • It is based on the concept of up-casting • A super class reference variable can refer subclass object • it is the type of the object being referred to • not the type of the reference variable • Super class contains a method that is overridden by a subclass • overridden method is called through a super class reference • Java determines which version of that method to execute based upon the type of the object being referred to at the time the call occurs • this determination is made at run time
  • 68.
    class A { voidcallme() { System.out.println("Inside A's callme method"); } } class B extends A { // override callme() 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"); } }
  • 69.
    class Dispatch { publicstatic 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 } } Output: Inside A’s callme method Inside B’s callme method Inside C’s callme method
  • 70.
    ABSTRACT CLASS • Aclass that is declared with abstract keyword, is known as abstract class • It can have abstract and non-abstract methods (method with body) • Abstraction is a process of hiding the implementation details and showing only functionality to user • Abstraction focus on what the object does instead of how it does it • It needs to be extended and its method implemented • Syntax: abstract class classname { } Abstract method • A method that is declared as abstract and does not have implementation • The method body will be defined by its subclass • Abstract method can never be final and static
  • 71.
    • Any classthat extends an abstract class must implement all abstract methods declared by the super class • Syntax: abstract returntype functionname (); //No definition • Syntax for abstract class and method: modifier abstract class className { //declare fields //declare methods abstract dataType methodName(); } modifier class childClass extends className { dataType methodName() { } }
  • 72.
    Rules 1. Abstract classesare not Interfaces. 2. may have concrete (complete) methods 3. may or may not have an abstract method. But if any class has one or more abstract methods, it must be compulsorily labeled abstract 4. can have Constructors, Member variables and Normal methods 5. For design purpose, a class can be declared abstract even if it does not contain any abstract methods 6. Reference of an abstract class can point to objects of its sub-classes thereby achieving run-time polymorphism Ex: Shape obj = new Rectangle(); 7. A class derived from the abstract class must implement all those methods that are declared as abstract in the parent class 8. If a child does not implement all the abstract methods of abstract parent class, then the child class must need to be declared abstract as well.
  • 73.
    //abstract parent class abstractclass Animal { //abstract method public abstract void sound(); } //Lion class extends Animal class public class Lion extends Animal { public void sound() { System.out.println(“Roars”); } public static void main(String args[]) { Animal obj = new Lion(); obj.sound(); } Output: Roars In the above code, Animal is an abstract class and Lion is a concrete class.
  • 74.
    abstract class Bank { abstractint getRateOfInterest(); } class SBI extends Bank { int getRateOfInterest() { return 7; } } class PNB extends Bank { int getRateOfInterest() { return 8; } } public class TestBank { public static void main(String args[]) { Bank b=new SBI();//if object is PNB, method of PNB will be invoked int interest=b.getRateOfInterest(); System.out.println(“Rate of Interest is: “+interest+” %”); b=new PNB(); System.out.println(“Rate of Interest is: “+b.getRateOfInterest()+” %”); } } Output: Rate of Interest is: 7 % Rate of Interest is: 8 %
  • 75.
    Final Methods andClasses • The final keyword in java is used to restrict the user. • The java final keyword can be applied to: Variable- To prevent constant variables method - To prevent method overriding class- To prevent inheritance • Java final variable • final keyword can be applied with the variables • final variable that have no value it is called blank final variable or uninitialized final variable. • It can be initialized in the constructor only. • blank final variable can be static also which will be initialized in the static block only.
  • 76.
    public class Vehicle { finalint speedlimit=60;//final variable void run() { speedlimit=400; } public static void main(String args[]) { Vehicle obj=new Vehicle(); obj.run(); } } • A final variable speed limit is defined within a class Vehicle. • try to change the value of this variable, we get an error • value of final variable cannot be changed, once a value is assigned to it. Output: /Vehicle.java:6: error: cannot assign a value to final variable speedlimit speedlimit=400; ^ 1 error
  • 77.
    Blank final variable •A final variable that is not initialized at the time of declaration is known as blank final variable. • We must initialize the blank final variable in constructor of the class otherwise it will throw a compilation error public class Vehicle { final int speedlimit; //blank final variable void run() { } public static void main(String args[]) { Vehicle obj=new Vehicle(); obj.run(); } } Output: /Vehicle.java:3: error: variable speedlimit not initialized in the default constructor final int speedlimit; //blank final variable ^ 1 error
  • 78.
    Java Final Method •method with the final keyword is called a final method and it cannot be overridden in the subclass. • final methods are inherited but they cannot be overridden class Bike{ final void run(){System.out.println("running");} } class Honda extends Bike{ void run(){System.out.println("running safely with 100kmph"); } public static void main(String args[]){ Honda honda= new Honda(); honda.run(); } } Output:Compile Time Error
  • 79.
    class XYZ { final voiddemo() { System.out.println(“XYZ Class Method”); } } public class ABC extends XYZ { public static void main(String args[]) { ABC obj= new ABC(); obj.demo(); } } Output: XYZ Class Method
  • 80.
    Java Final Class •Final class is a class that cannot be extended i.e. it cannot be inherited. • A final class can be a subclass but not a super class. • Declaring a class as final implicitly declares all of its methods as final • Several classes in Java are final e.g. String, Integer, and other wrapper classes. • The final keyword can be placed either before or after the access specifier • Syntax: final public class A { OR //code } public final class A { //code }
  • 81.
    final class XYZ { } publicclass ABC extends XYZ { void demo() { System.out.println(“My Method”); } public static void main(String args[]) { ABC obj= new ABC(); obj.demo(); } } Output: /ABC.java:5: error: cannot inherit from final XYZ public class ABC extends XYZ ^ 1 error
  • 82.
    INTERFACES • An interfacein java is a blueprint of a class • An interface is a reference type in Java • similar to class • collection of abstract methods • may also contain constants, default methods, static methods, and nested types. • Method bodies exist only for default methods and static methods An interface is similar to a class in the following ways: • interface can contain any number of methods • interface is written in a file with a .java extension, with the name of the interface matching the name of the file • byte code of an interface appears in a .class file • Interfaces appear in packages, and their corresponding byte code file must be in a directory structure that matches the package name
  • 83.
    Uses of interface: •java does not support multiple inheritance in case of class, it can be achieved by using interface • It is also used to achieve loose coupling • Interfaces are used to implement abstraction Defining an Interface • An interface is defined much like a class
  • 84.
    Syntax: accessspecifier interface interfacename { return-typemethod-name1(parameter-list); return-type method-name2(parameter-list); type final-varname1 = value; type final-varname2 = value; // ... return-type method-nameN(parameter-list); type final-varnameN = value; }
  • 85.
    /* File name: Animal.java */ interface Animal { public void eat(); public void travel(); } Implementing an Interface • Once an interface has been defined, one or more classes can implement that interface • To implement an interface, the ‘implements’ clause included in a class definition and then methods defined by the interface are created. Syntax: class classname [extends superclass] [implements interface [,interface...]] { // class-body }
  • 86.
    Rules • A classcan implement more than one interface at a time. • A class can extend only one class, but can implement many interfaces. • An interface can extend another interface, in a similar way as a class can extend another class /* File name : Mammal.java */ public class Mammal implements Animal { public void eat() { System.out.println(“Mammal eats”); } public void travel() { System.out.println(“Mammal travels”); }
  • 87.
    public int noOfLegs() { return0; } public static void main(String args[]) { Mammal m = new Mammal(); m.eat(); m.travel(); } } Output: Mammal eats Mammal travels
  • 88.
    import java.io.*; // Asimple interface interface Sample { final String name = “Shree”; void display(); } // A class that implements interface. public class testClass implements Sample { public void display() { System.out.println(“Welcome”); } public static void main (String[] args) { testClass t = new testClass(); t.display(); System.out.println(name); } } Output: Welcome Shree
  • 89.
    Nested Interface • Aninterface can be declared as a member of a class or another interface • Such an interface is called a member interface or a nested interface • A nested interface can be declared as public, private, or protected interface MyInterfaceA { void display(); interface MyInterfaceB { void myMethod(); } }
  • 90.
    public class NestedInterfaceDemoimplements MyInterfaceA.MyInterfaceB { public void myMethod() { System.out.println(“Nested interface method”); } public static void main(String args[]) { MyInterfaceA.MyInterfaceB obj= new NestedInterfaceDemo(); obj.myMethod(); } } Output: Nested interface method
  • 91.
    Multiple inheritance inJava 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(); }
  • 92.
    class A7 implementsPrintable,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 Interface inheritance
  • 93.
    Aspect for comparison Class Interface BasicA class is instantiated to create objects An interface can never be instantiated as the methods are unable to perform any action on invoking Keyword class Interface Access specifier The members of a class can be private, public or protected. The members of an interface are always public Methods The methods of a class are defined to perform a specific action The methods in an interface are purely abstract inheritance A class can implement any number of interfaces and can extend only one class. An interface can extend multiple interfaces but cannot implement any interface. Inheritance keyword extends Implements Constructor A class can have constructors to initialize the variables. An interface can never have a constructor as there is hardly any variable to initialize.
  • 94.
    ABSTRACT CLASS INTERFACE 1)Abstract class can have abstract and non- abstract methods Interface can have only abstract methods. 2) Abstract class doesn't support multiple inheritance. Interface supports multiple inheritance. 3) Abstract class can have final, non-final, static and non-static variables Interface has only static and final variables 4) Abstract class can provide the implementation of interface. Interface can't provide the implementation of abstract class. 5) The abstract keyword is used to declare abstract class The interface keyword is used to declare interface. 6) An abstract class can extend another Java class and implement multiple Java interfaces. An interface can extend another Java interface only. 7) An abstract class can be extended using keyword extends. An interface class can be implemented using keyword implements 8) A Java abstract class can have class members like private, protected, etc. Members of a Java interface are public by default.