0% found this document useful (0 votes)
18 views

Java Unit2

Java notes 3

Uploaded by

Nagendra mutyala
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

Java Unit2

Java notes 3

Uploaded by

Nagendra mutyala
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

JAVA PROGRAMMING

UNIT-2
INHERITANCE
Inheritance: Inheritance is the process by which objects of one class acquire the properties of
objects of another class. Inheritance supports the concept of hierarchical classification. A deeply
inherited subclass inherits all of the attributes from each of its ancestors in the class hierarchy.

Most people naturally view the world as made up of objects that are related to each
other in a hierarchical way.

Inheritance: A new class (subclass, child class) is derived from the existing class(base class,
parent class).

Main uses of Inheritance:

1. Reusability

2. Abstraction

Syntax:

Class Sub-classname extends Super-classname

{ Declaration of variables;

Declaration of methods;

}
JAVA PROGRAMMING

Super class: In Java a class that is inherited from is called a super class.

Sub class: The class that does the inheriting is called as subclass.

Therefore, a subclass is a specialized version of a superclass. It inherits all of the instance


variables and methods defined by the superclass and add its own, unique elements.

extends: To inherit a class, you simply incorporate the definition of one class into another by
using the extends keyword.

The “extends” keyword indicates that the properties of the super class name are extended to the
subclass name. The sub class now contain its own variables and methods as well those of the
super class. This kind of situation occurs when we want to add some more properties to an
existing class without actually modifying the super class members.

// A simple example of inheritance.

// Create a superclass.
class A
{
int i, j;
void showij()
{
System.out.println("i and j: " + i + " " + j);
}
}
// Create a subclass by extending class A.
class B extends A
{
int k;
void showk()
{
System.out.println("k: " + k);
}
void sum() {
System.out.println("i+j+k: " + (i+j+k));
}
}
class SimpleInheritance
{
public static void main(String args[])
{
JAVA PROGRAMMING

A superOb = new A();


B subOb = new B();
// The superclass may be used by itself.
superOb.i = 10;
superOb.j = 20;
System.out.println("Contents of superOb: ");
superOb.showij();
System.out.println();
/* The subclass has access to all public members of
its superclass. */
subOb.i = 7;
subOb.j = 8;
subOb.k = 9;
System.out.println("Contents of subOb: ");
subOb.showij();
subOb.showk();
System.out.println();
System.out.println("Sum of i, j and k in subOb:");
subOb.sum();
}
}
Output:
D:\aruns>javac SimpleInheritance.java
D:\aruns>java SimpleInheritance
Contents of superOb:
i and j: 10 20
Contents of subOb:
i and j: 7 8
k: 9
Sum of i, j and k in subOb:
i+j+k: 24

Hierarchical abstractions:
Hierarchical abstractions of complex systems can also be applied to computer programs. The
data from a traditional process-oriented program can be transformed by abstraction into its
component objects.

A sequence of process steps can become a collection of messages between these objects.
Thus, each of these objects describes its own unique behavior.

 You can treat these objects as concrete entities that respond to messages telling them to do
something. This is the essence of object-oriented programming.
JAVA PROGRAMMING

Types of Inheritance are use to show the Hierarchical abstractions. They are:

 Single Inheritance

 Multiple Inheritance

 Hierarchical Inheritance

 Multilevel Inheritance

 Hybrid Inheritance

Single Inheritance: Simple Inheritance is also called as single Inheritance. Here One subclass is
deriving from one super class.

SUPER CLASS A
EXTENDS

SUB CLASS B

Example:
//single inheritance
//consists of only one super class and one sub class
class superclass
{
int a=10,b=20;
void sup_method()
{
System.out.println("This is super class method");
}

}
class subclass extends superclass
{
JAVA PROGRAMMING

int c=30;
void display()
{
System.out.println("The given values are:"+a+","+b+ " & " +c);
}
}
class single_inheritance
{
public static void main(String ar[])
{
subclass obj=new subclass();
obj.sup_method();
obj.display();
}
}

Output:
F:\JAVA Programs for ECE>javac single_inheritance.java
F:\JAVA Programs for ECE>java single_inheritance
This is super class method
The given values are:10,20 & 30

Multiple Inheritance: Deriving one subclass from more than one super classes is called
multiple inheritance.

INTERFACE1 INTERFACE2
A B

(Animal) (Bird)
IMPLEMENTS
SUBCLASS(InterfaceDemo2)

We know that in multiple inheritance, sub class is derived from multiple super classes. If two
super classes have same names for their members then which member is inherited into the sub
class is the main confusion in multiple inheritance. This is the reason; Java does not support the
JAVA PROGRAMMING

concept of multiple inheritance. This confusion is reduced by using multiple interfaces to


achieve multiple inheritance.

Interface: An interface is a class containing a group of constants and method declarations that
does not provide implementation. In essence, an interface allows you to specify what a class
must do, but not how to do.

Interface syntax:

access interface name


{
return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
type varname1 = value;
type varname2 = value;
// ...
return-type method-nameN(parameter-list);
type varnameN = value;
}

 All the methods in an interface must be abstract and public. If we not mention these
keywords then JVM will treats all methods as public and abstract implicitly.

 All the constants are treated as public, final and static.


Example:
interface Animal
{
public abstract void moves();
}
interface Bird
{
void fly();
JAVA PROGRAMMING

}
public class InterfaceDemo2 implements Animal,Bird
{
public void moves()
{
System.out.println("animal move on land");
}
public void fly()
{
System.out.println("birds fly in air");
}
public static void main(String args[])
{
InterfaceDemo2 id=new InterfaceDemo2();
id.moves();
id.fly();
}
}
Output:
D:\aruns>javac InterfaceDemo2.java
D:\aruns>java InterfaceDemo2
animal move on land
birds fly in air

Hierarchical Inheritance: Only one base class but many derived classes.
SUPERCLASS
Figure

EXTENDS
Rectangle Triangle SUBCLASS
Example:
//hierarchical inheritance
class parent
{
int p1=1000;
int p2=2000;
}
//subclass1
class child1 extends parent
{
int p3=3000;
JAVA PROGRAMMING

void display()
{
System.out.println("Child1 Properties");
System.out.println(p1+" "+p2+" "+p3);
System.out.println("----------------------");
}
}
class child2 extends parent
{
int p4=6000;

void show()
{
System.out.println("Child2 Properties");
System.out.println(p1+" "+p2+" "+p4);
}
}
class hierarchical_inheritance
{
public static void main(String ar[])
{
child1 obj=new child1();
obj.display();
child2 obj1=new child2();
obj1.show();
}
}

Output:
F:\JAVA Programs for ECE>javac hierarchical_inheritance.java
F:\JAVA Programs for ECE>java hierarchical_inheritance
Child1 Properties
1000 2000 3000
----------------------
Child2 Properties
1000 2000 6000
JAVA PROGRAMMING

Multilevel Inheritance: In multilevel inheritance the class is derived from the derived class.

SUPER-CLASS
A
extends
B
SUB-CLASS

C extends

SUB-SUBCLASS

Example:
//multi-level inheritance
class X
{
int rollno=401;
}
class Y extends X
{
String name="ABC";
}
class Z extends Y
{
String college="NEC";
void display()
{
System.out.println("Roll Number= "+rollno+ " Name= "+ name+ "
College= "+college);
}
}
class multilevel_inheritance
{
public static void main(String ar[])
{
Z obj=new Z();
obj.display();
}
}
JAVA PROGRAMMING

Output:
F:\JAVA Programs for ECE>javac multilevel_inheritance.java
F:\JAVA Programs for ECE>java multilevel_inheritance
Roll Number= 401 Name= ABC College= NEC

Hybrid Inheritance: It is a combination of multiple and hierarchical inheritance.

A
HIERARCHICAL
B C

MULTIPLE
D

“super” Keyword:
Whenever a subclass needs to refer to its immediate super class, it can do so by the use of the
keyword super.

Super has the two general forms.

1. super (args-list): calls the Super class’s constructor.

2. super.member: To access a member of the super class that has been hidden by a member of a
subclass. Member may be variable or method.

Use: Overridden methods allow Java to support Run-time polymorphism. This leads to
Robustness by Reusability.

The keyword ‘super’:

 super can be used to refer super class variables as: super.variable

 super can be used to refer super class methods as: super.method ()


JAVA PROGRAMMING

 super can be used to refer super class constructor as: super (values)

1. Example program for super can be used to refer super class constructor as: super
(values)

class Figure
{
double dim1;
double dim2;
Figure(double a, double b)
{
dim1=a;
dim2=b;
}
}
class Rectangle extends Figure
{
Rectangle(double a,double b)
{ calling super class constructor
super(a,b);
}
double area()
{
System.out.println("Inside area for rectangle");
return dim1*dim2;
}
}
class Triangle extends Figure
{
Triangle(double a,double b)
{
super(a,b);
}
double area()
{
System.out.println("Inside area for triangle");
return dim1*dim2/2;
}
}
class FindAreas
{
public static void main(String args[])
{
Rectangle r=new Rectangle(9,5);
Triangle t=new Triangle(10,8);
System.out.println("area is"+r.area());
JAVA PROGRAMMING

System.out.println("area is"+t.area());
}
}
Output:
D:\aruns>javac FindAreas.java
D:\aruns>java FindAreas
Inside area for rectangle
area is45.0
Inside area for triangle
area is40.0
2.Accessing the member of a super class:

The second form of super acts somewhat like this, except that it always refers to the
superclass of the subclass in which it is used.

Syntax: super. member;

Here, member can be either a method or an instance variable. This second form of super is most
applicable to situations in which member names of a subclass hide members by the same name
in the superclass. Consider this simple class hierarchy:

// using super to overcome name hiding.

class A
{
int i;
}
// Create a subclass by extending class A.
class B extends A
{
int i; // this i hides the i in A
B(int a, int b)
{
super.i = a; // i in A
i = b; // i in B
}
void show()
{
System.out.println("i in superclass: " + super.i);
System.out.println("i in subclass: " + i);
}
}
class UseSuper
{
JAVA PROGRAMMING

public static void main(String args[])


{
B subOb = new B(1, 2);
subOb.show();
}
}
Output:
D:\aruns>javac UseSuper.java
D:\aruns>java UseSuper
i in superclass: 1
i in subclass: 2
Super uses: super class’s method access

import java.io.*;
class A
{
void display()
{
System.out.println("hi");
}
}
class B extends A
{
void display()
{ calling super class method
super.display();
System.out.println("hello");
}
static public void main(String args[])
{
B b=new B();
b.display();
}
}
Output:
D:\aruns>javac B.java
D:\aruns>java B
hi
hello

Note: Super key word is used in sub class only.


The statement calling super class constructor should be the first one in sub class constructor.
JAVA PROGRAMMING

Abstract classes:
A method with method body is called concrete method. In general any class will have all
concrete methods.

A method without body is called abstract method.

Syntax: abstract datatype methodname (parameter-list);

A class that contains abstract method is called abstract class.

It is possible to implement the abstract methods differently in the subclasses of an abstract
class.

These different implementations will help the programmer to perform different tasks
depending on the need of the sub classes. Moreover, the common members of the abstract class
are also shared by the sub classes.

 The abstract methods and abstract class should be declared using the keyword abstract.

 We cannot create objects to abstract class because it is having incomplete code.


Whenever an abstract class is created, subclass should be created to it and the
abstract methods should be implemented in the subclasses, then we can create objects to
the subclasses.

 An abstract class is a class with zero or more abstract methods

 An abstract class contains instance variables & concrete methods in addition to abstract
methods.

 It is not possible to create objects to abstract class.

 But we can create a reference of abstract class type.

 All the abstract methods of the abstract class should be implemented in its sub classes.

 If any method is not implemented, then that sub class should be declared as ‘abstract’.
JAVA PROGRAMMING

 Abstract class reference can be used to refer to the objects of its sub classes.

 Abstract class references cannot refer to the individual methods of sub classes.

 A class cannot be both ‘abstract’ & ‘final’.

e.g.: final abstract class A // invalid


Abstraction refers to the act of representing essential features without including the background
details or explanations. Classes use the concept of abstraction and are defined as a list of
attributes and methods to operate on these attributes. They encapsulate all the essential features
of the objects that are to be created since the classes use the concept of data abstraction they are
known as Abstract Data Types.

An abstract class can be sub classed and can’t be instantiated.

Example: // Using abstract methods and classes.


abstract class Figure
{
double dim1;
double dim2;
Figure (double a, double b)
{
dim1 = a;
dim2 = b;
}
abstract double area (); // area is now an abstract method
}
class Rectangle extends Figure
{
Rectangle (double a, double b)
{
super (a, b);
}
double area () // override area for rectangle
{
System.out.println ("Inside Area of Rectangle.");
return dim1 * dim2;
}
}
class Triangle extends Figure
{
JAVA PROGRAMMING

Triangle (double a, double b)


{
super (a, b);
}
double area() // override area for right triangle
{
System.out.println ("Inside Area of Triangle.");
return dim1 * dim2 / 2;
}
}
class AbstractAreas
{
public static void main(String args[])
{
// Figure f = new Figure(10, 10); // illegal now
Rectangle r = new Rectangle(9, 5);
Triangle t = new Triangle(10, 8);
System.out.println("Area is " + r.area());
System.out.println("Area is " + t.area());
}
}
Output:
D:\aruns>javac AbstractAreas.java
D:\aruns>java AbstractAreas
Inside area for Rectangle.
Area is 45.0
Inside are for Triangle.
Area is 40.0

“final” Keyword

”final” is a keyword in Java which generically means, cannot be changed once created. Final
behaves very differently when variables, methods and classes. Any final keyword when declared
with variables, methods and classes specifically means:

 A final variable cannot be reassigned once initialized.

 A final method cannot be overridden.

 A final class cannot be extended.


JAVA PROGRAMMING

 Classes are usually declared final for either performance or security reasons. Final methods
work like inline code of C++.

“final” with variables:

Final variables work like const of C-language that can’t be altered in the whole program. That is,
final variables once created can’t be changed and they must be used as it is by all the program
code.

Example program:

import java.io.*;
class FinalVar
{
int x=10;
final int y=20;
System.out.println("x is:"+x);
System.out.println("y is:"+y);
x=30;
y=40;
System.out.println("x is:"+x);
System.out.println("y is:"+y);
}
}
Output:
Cannot assign a value to final variable y
“final” with methods:
Generally, a super class method can be overridden by the subclass if it wants a different
functionality. Or, it can call the same method if it wants the same functionality. If the super class
desires that the subclass should not override its method, it declares the method as final. That is,
methods declared final in the super class cannot be overridden in the subclass(else it is
compilation error). But, the subclass can access with its object as usual.

Example program:

import java.io.*;

class A
JAVA PROGRAMMING

final void display()

System.out.println("hi");

class B extends A

void display()

super.display();

System.out.println("hello");

static public void main(String args[])

B b=new B();

b.display();

Output:

Display() in B cannot override display() in A; overridden method is


final.
JAVA PROGRAMMING

“final” with classes:


If we want the class not be sub-classed(or extended) by any other class, declare it final. Classes
declared final can not be extended. That is, any class can use the methods of a final class by
creating an object of the final class and call the methods with the object(final class object).

Example program:

import java.io.*;
final class Demo1
{
public void display()
{
System.out.println("hi");
}
}
public class Demo3 extends Demo1
{
public static void main(String args[])
{
Demo1 d=new Demo1();
d.display();
}}
Output:
D:\aruns>javac Demo3.java
Demo3.java:9: cannot inherit from final Demo1
public class Demo3 extends Demo1
^
1 error

Polymorphism:
Polymorphism came from the two Greek words ‘poly’ means many and ‘morphos’ means
forms.
If the same method has ability to take more than one form to perform several tasks
then it is called polymorphism.
It is of two types:
 Dynamic polymorphism(Runtime polymorphism)

 Static polymorphism(Compile time polymorphism)


Dynamic Polymorphism:
JAVA PROGRAMMING

The polymorphism exhibited at run time is called dynamic polymorphism. In this dynamic
polymorphism a method call is linked with method body at the time of execution by JVM. Java
compiler does not know which method is called at the time of compilation. This is also
known as dynamic binding or run time polymorphism.

Method overloading and method overriding are examples of Polymorphism in Java.

o Method Overloading: Writing two or more methods with the same name with different
parameters is called method over loading.. In method overloading JVM understands which
method is called depending upon the difference in the method parameters. The difference may
be due to the following:

Ø There is a difference in the no. of parameters.

void add (int a,int b)

void add (int a,int b,int c)

Ø There is a difference in the data types of parameters.

void add (int a,float b)

void add (double a,double b)

Ø There is a difference in the sequence of parameters.

void swap (int a,char b)

void swap (char a,int b)

// overloading of methods

class Sample
{
void add(int a, int b)
{
System.out.println ("sum of two="+ (a+b));
}
JAVA PROGRAMMING

void add(int a, int b, int c)


{
System.out.println ("sum of three="+ (a+b+c));
}
}
class OverLoad
{
public static void main(String[] args)
{
Sample s=new Sample ( );
s.add (20, 25);
s.add (20, 25, 30);
}
}
Output:
D:\aruns>javac OverLoad.java
D:\java OverLoad
sum of two=45
sum of three=75
o Method Overriding: Writing two or more methods in super & sub classes with same name
and same parameters is called method overriding. In method overriding JVM executes a
method depending on the type of the object.

//overriding of methods --------------- Dynamic polymorphism

class Animal
{
void move()
{
System.out.println ("Animals can move");
}
}
class Dog extends Animal
{
void move()
{
System.out.println ("Dogs can walk and run");
}
}
public class OverRide
{
public static void main(String args[])
{
Animal a = new Animal (); // Animal reference and object
Animal b = new Dog (); // Animal reference but Dog object
JAVA PROGRAMMING

a.move (); // runs the method in Animal class


b.move (); //Runs the method in Dog class
} }
Output:
D:\aruns>javac OverRide.java
D:\aruns>java OverRide
Animals can move
Dogs can walk and run
Achieving method overloading & method overriding using instance methods is an example of
dynamic polymorphism.

Benefits of Inheritance:

 Increased reliability

 Software reusability
 Code sharing

 To create software components

 Consistency of interface

 Polymorphism
 Information hiding

 Rapid prototyping
Costs of inheritance:
 Program size

 Execution speed

 Program complexity
 Message-passing

You might also like