© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
1
Day 3
Inheritance
Advance Class Features
Abstraction
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
2
Inheritance
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
3
Inheritance Basic
• In Java, the classes can be derived from other classes.
• The derived class can inherit the fields and methods of base class.
• A class that is derived from another class is called a subclass.
• The class from which the subclass is derived is called as superclass.
• The syntax to derive a class:
class <classname> extends <superclassname>
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
4
Inheritance Basic (Contd.)
• An example to derive a class:
class Base{
}
class Sub extends Base{
}
• In the preceding code snippet, Base is the super class and Sub is the
sub class.
• Java supports following types of inheritance:
• Single inheritance
• Multilevel inheritance
• Hierarchical inheritance
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
5
Inheritance Basic (Contd.)
Class A
Class B
Class A
Class B
Class C
Class A
Class B
Class D Class E
Class C
Class F
Single Inheritance Multilevel Inheritance Hierarchical Inheritance
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
6
Inheritance Basic (Contd.)
• An example to implement single inheritance:
public class Base {
int baseA;
Base(){
baseA=20;
}
void printBase(){
System.out.println("baseA value="+baseA);
}
}
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
7
Inheritance Basic (Contd.)
public class Sub extends Base{
int subA;
Sub(){
subA=67;
}
void printSub(){
System.out.println("baseA value="+baseA);
System.out.println("subA value="+subA);
}
}
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
8
Inheritance Basic (Contd.)
public class InheritanceDemo {
public static void main(String args[]){
Sub obj=new Sub();
obj.printSub();
obj.printBase();
}
}
• The preceding code output will be:
baseA value=20
subA value=67
baseA value=20
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
9
Inheritance Basic (Contd.)
• In the preceding code, the base class object is not created. However,
from the output you can notice that base class constructor was
invoked.
• When a sub class object is created the sub class constructor is
invoked. From the sub class constructor the JVM internally invokes
the super class constructor.
• You can also notice that the sub class objects are able to access the
super class members.
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
10
Inheritance Basic (Contd.)
• An example to implement multilevel inheritance:
public class Circle {
double radius;
public Circle() {
radius = 1.0;
}
public Circle(double r) {
radius = r;
}
public double getRadius() {
return radius;
}
public double getArea() {
return radius*radius*3.14;
}
}
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
11
Inheritance Basic (Contd.)
public class Cylinder extends Circle {
private double height;
public Cylinder() {
height = 1.0;
}
public Cylinder(double r, double h) {
setRadius(r);
height = h;
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
public double getVolume() {
return getArea()*height;
}
}
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
12
Inheritance Basic (Contd.)
public class InheritanceDemo {
public static void main(String args[]){
Cylinder cy1 = new Cylinder();
System.out.println("Radius is " + cy1.getRadius()
+ " Height is " + cy1.getHeight()
+ " Base area is " + cy1.getArea()
+ " Volume is " + cy1.getVolume());
Cylinder cy2 = new Cylinder(5.0, 2.0);
System.out.println("Radius is " + cy2.getRadius()
+ " Height is " + cy2.getHeight()
+ " Base area is " + cy2.getArea()
+ " Volume is " + cy2.getVolume());
}
}
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
13
Inheritance Basic (Contd.)
• The preceding code output will be:
Radius is 1.0 Height is 1.0 Base area is 3.14 Volume
is 3.14
Radius is 5.0 Height is 2.0 Base area is 78.5 Volume
is 157.0
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
14
Inheritance Basic (Contd.)
• An example to implement hierarchical inheritance:
public class Shapes {
int noOfSides;
void display(){
System.out.println("No of sides:"+noOfSides);
}
}
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
15
Inheritance Basic (Contd.)
public class Rectangle extends Shapes {
Rectangle(){
noOfSides=4;
}
}
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
16
Inheritance Basic (Contd.)
public class Pentagon extends Shapes {
public Pentagon() {
noOfSides=5;
}
}
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
17
Inheritance Basic (Contd.)
public class Hexagon extends Shapes {
public Hexagon() {
noOfSides=6;
}
}
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
18
Inheritance Basic (Contd.)
public class InheritanceDemo {
public static void main(String args[]){
Shapes sObj=new Shapes();
Rectangle rObj =new Rectangle();
Pentagon pObj=new Pentagon();
Hexagon hObj=new Hexagon();
sObj.display();
rObj.display();
pObj.display();
hObj.display();
}
}
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
19
Inheritance Basic (Contd.)
• The output of the preceding code will be:
No of sides:0
No of sides:4
No of sides:5
No of sides:6
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
20
Inheritance Basic (Contd.)
• Consider the following code snippet:
class Shapes {
int noOfSides;
void displayShapes(){
System.out.println("No of sides:"+noOfSides);
}
}
class Rectangle extends Shapes {
Rectangle(){
noOfSides=4;
}
void displayRectangle(){
System.out.println("Rectangle");
}
}
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
21
Inheritance Basic (Contd.)
public class InheritanceDemo {
public static void main(String args[]){
Shapes sObj=new Rectangle();
sObj.displayShapes();
}
}
• In the preceding code, the reference variable sObj, refers to the
object of Rectangle class. Therefore, the
sObj.displayShapes();statement will raise a compilation
error.
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
22
Use of super Keyword
• The super keyword is used to refer an instance of immediate parent class
object.
• An example to work with super keyword:
public class Base {
int val;
Base(){
val=20;
}
void printBase(){
System.out.println("Value="+val);
}
}
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
23
Use of super Keyword (Contd.)
public class Sub extends Base{
int val;
Sub(){
val=67;
}
void printSub(){
System.out.println("Base class
Value="+super.val);
System.out.println("Sub class value="+val);
}
}
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
24
Use of super Keyword (Contd.)
public class InheritanceDemo {
public static void main(String args[]){
Sub sObj=new Sub();
sObj.printBase();
sObj.printSub();
}
}
• The preceding code output will be:
Value=20
Base class Value=20
Sub class value=67
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
25
Use of super Keyword (Contd.)
• When a sub class constructor does not explicitly calls the super class
constructor, then the compiler will insert a super() statement.
• This statements invokes the super class constructor without parameter.
• Consider the following code:
class Base{
int baseX;
Base(){
this(10);
System.out.println("Base()");
}
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
26
Use of super Keyword (Contd.)
Base(int x){
baseX=x;
System.out.println("Base(int)");
}
}
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
27
Use of super Keyword (Contd.)
class Sub extends Base{
int subX;
Sub(){
subX=20;
System.out.println("Sub()");
}
}
public class SuperDemo {
public static void main(String args[]){
Sub sObj=new Sub();
}
}
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
28
Use of super Keyword (Contd.)
• The preceding code output will be:
Base(int)
Base()
Sub()
• Now, in the preceding code if you remove the Base(){} constructor
definition, an compilation error will be raised in the Sub(){}
constructor definition.
• To rectify this error, the Base class constructor should be explicitly
called from Sub class constructor. This can be achieved by adding the
following code snippet to the Sub() constructor:
super(7);
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
29
Use of super Keyword (Contd.)
• The super() statement must be the first statementinside the sub class
constructor.
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
30
Overriding
• Overriding is feature that enables a sub class to redefine a super class
method.
• The overriding method has the same name, number and type of
parameters, and return type as the method that it overrides.
• In Java, runtime polymorphism is achieved through overriding.
• Runtime polymorphism means that the exact method that is bound
to the object is not known at compile time.
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
31
Overriding (Contd.)
• An example to work with overridden methods:
public class Base {
int val;
Base(){
val=20;
}
void display(){
System.out.println("Value="+val);
}
}
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
32
Overriding (Contd.)
public class Sub extends Base{
int val;
Sub(){
val=67;
}
void display(){
System.out.println("Base class
Value="+super.val);
System.out.println("Sub class value="+val);
}
}
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
33
Overriding (Contd.)
public class InheritanceDemo {
public static void main(String args[]){
Base bObj=new Base();
Sub sObj=new Sub();
bObj.display();
sObj.display();
}
• The preceding code output will be:
Value=20
Base class Value=20
Sub class value=67
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
34
Overriding (Contd.)
• Consider the following code snippet:
class Shapes {
int noOfSides;
public void displayShapes(){
System.out.println("No of sides:"+noOfSides);
}
}
class Rectangle extends Shapes {
Rectangle(){
noOfSides=4;
}
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
35
Overriding (Contd.)
void displayShapes(){
System.out.println("Rectangle");
}
}
• The preceding code will generate a compilation error, because the
base class method displayShape() access control level is more than
the overridden method.
• The following code is a valid overridden method example :
class Shapes {
int noOfSides;
void displayShapes(){
System.out.println("No of sides:"+noOfSides);
}
}
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
36
Overriding (Contd.)
class Rectangle extends Shapes {
Rectangle(){
noOfSides=4;
}
public void displayShapes(){
System.out.println("Rectangle");
}
}
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
37
Overriding (Contd.)
• Consider the following code:
class Shapes {
int noOfSides;
void displayShapes(){
System.out.println("No of sides:"+noOfSides);
}
}
class Rectangle extends Shapes {
Rectangle(){
noOfSides=4;
}
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
38
Overriding (Contd.)
void displayShapes(){
System.out.println("Rectangle");
}
}
public class InheritanceDemo {
public static void main(String args[]){
Shapes sObj=new Rectangle();
sObj.displayShapes();
}
}
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
39
Overriding (Contd.)
• The preceding code output will be:
Rectangle
• The behavior demonstrated in the preceding code is referred
as virtual method invocation.
• The JVM calls the appropriate method for the object that is
referred by the reference variable.
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
40
Advance Class Features
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
41
Static Variables
• Variables that have the static modifier are called static variables or
class variables.
• Static variable belongs to the class and not to object.
• A single copy static variable is shared by all instances of the class.
• A static variable can be accessed outside the class by using the class
name.
• The syntax to access a static variable:
<classname>.<staticvariablename>
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
42
Static Variables (Contd.)
• An example to work with static variable:
public class StaticVarDemo {
static int count;
StaticVarDemo(){
count++;
}
void display(){
System.out.println("The count="+count);
}
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
43
Static Variables (Contd.)
public static void main(String args[]){
StaticVarDemo obj1=new StaticVarDemo();
obj1.display();
StaticVarDemo obj2=new StaticVarDemo();
obj2.display();
obj1.display();
}
}
• The preceding code output will be:
The count=1
The count=2
The count=2
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
44
Static Methods
• Methods that have the static modifier are called static methods.
• Static methods belongs to the class and not to object.
• A static method can access only static data.
• A static method cannot refer to this or super keywords.
• A static method can be overloaded. However, they can not be
overridden.
• A static method can be accessed outside the class by using the class
name.
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
45
Static Methods (Contd.)
• The syntax to access a static method:
<classname>.<methodname>
• Example:
class Test{
static void display(){
System.out.println("display()");
}
}
public class StaticMethodDemo {
static void show(){
StaticMethodDemo o=new StaticMethodDemo();
System.out.println("display()");
Test.display();
}
}
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
46
Static Methods (Contd.)
• An example of to work static method:
public class StaticMethodDemo {
static void display(){
System.out.println("Static display method");
}
public static void main(String args[]) {
display();
}
}
• The preceding code output will be:
Static display method
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
47
Static Methods (Contd.)
• Consider the following code snippet:
void display(){
System.out.println("display()");
}
static void show(){
System.out.println("display()");
display();
}
• The preceding code snippet will generate a compilation error because
a non static method can not be called from a static method. However,
you can create an instance of the class and call the non static method
using the reference variable.
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
48
Static Block
• A static block is a block of code enclosed in braces, { }, and preceded
by the static keyword.
• The code in static blocks is executed when the class is loaded by JVM.
• A static block is used to initialize the static variables.
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
49
Static Block (Contd.)
• An example to work with static block:
public class StaticBlockDemo {
static int val;
static
{
val=10;
}
StaticBlockDemo(){
val++;
}
void display(){
System.out.println("Value="+val);
}
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
50
Static Block (Contd.)
public static void main(String args[]){
StaticBlockDemo obj=new StaticBlockDemo();
obj.display();
}
}
• The preceding code output will be:
Value=11
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
51
Static Import
• Static import allows to import static members of class and use them,
as they are declared in the same class.
• The syntax for static import:
import static <packagename>.<classname>.*;
• An example for static import:
import static java.lang.Math.*;
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
52
Static Import (Contd.)
• An example to work with static import:
import static java.lang.Math.*;
public class StaticImportDemo {
public static void main(String args[]) {
double circleArea=PI*pow(4, 2);
System.out.println("Area of
circle:"+circleArea);
}
}
• The preceding code output will be:
Area of circle:50.26548245743669
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
53
Abstraction
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
54
Abstract Class
• An abstract class is a class that is declared abstract.
• Abstract classes cannot be instantiated, but they can be sub classed.
• The syntax to define abstract class:
<accessmodifier> abstract class <classname>{
}
• An example to define abstract class:
abstract class Instrument {
……….
}
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
55
Abstract Method
• An abstract method is a method that is declared without an
implementation.
• The syntax to declare an abstract method:
<accessmodifier> abstract
<returntype><methodname>(parameterlist);
• An example to declare an abstract method:
abstract public void play();
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
56
Abstract Class and Method (Contd.)
• An example to work with abstract class and method:
abstract class Instrument {
protected String name;
abstract public void play();
}
abstract class StringedInstrument extends Instrument {
protected int numberOfStrings;
}
public class ElectricGuitar extends StringedInstrument {
public ElectricGuitar() {
super();
this.name = "Guitar";
this.numberOfStrings = 6;
}
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
57
Abstract Class and Method (Contd.)
public class ElectricGuitar extends StringedInstrument {
public ElectricGuitar() {
super();
this.name = "Guitar";
this.numberOfStrings = 6;
}
public ElectricGuitar(int numberOfStrings) {
super();
this.name = "Guitar";
this.numberOfStrings = numberOfStrings;
}
public void play() {
System.out.println("An electric " + numberOfStrings + "-string "
+ name
+ " is rocking!");
}
}
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
58
Abstract Class and Method (Contd.)
public class ElectricBassGuitar extends StringedInstrument {
public ElectricBassGuitar() {
super();
this.name = "Bass Guitar";
this.numberOfStrings = 4;
}
public ElectricBassGuitar(int numberOfStrings) {
super();
this.name = "Bass Guitar";
this.numberOfStrings = numberOfStrings;
}
public void play() {
System.out.println("An electric " + numberOfStrings + "-string " + name
+ " is rocking!");
}
}
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
59
Abstract Class and Method (Contd.)
public class Execution {
public static void main(String[] args) {
ElectricGuitar guitar = new ElectricGuitar();
ElectricBassGuitar bassGuitar = new ElectricBassGuitar();
guitar.play();
bassGuitar.play();
guitar = new ElectricGuitar(7);
bassGuitar = new ElectricBassGuitar(5);
guitar.play();
bassGuitar.play();
}
}
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
60
Abstract Class and Method (Contd.)
• The preceding code output will be:
An electric 6-string Guitar is rocking!
An electric 4-string Bass Guitar is rocking!
An electric 7-string Guitar is rocking!
An electric 5-string Bass Guitar is rocking!
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
61
Abstract Class and Method (Contd.)
• An abstract class can have abstract and/or non abstract methods.
• An abstract method can be declared only inside an abstract class or
an interface.
• An abstract class can extend another abstract class.
• When an abstract class extends another abstract class, it may or may
not override the abstract methods of the abstract base class.
• However, when a non abstract sub class inherits an abstract class,
then the sub class must override all the abstract methods.
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
62
Final Class
• Final class is class defined with final keyword.
• If a class should not be sub classed then a final class should be
created.
• The syntax to define a final class:
<access modifier> final class <class name>{
}
• An example to define a final class:
public final class Mobile {
}
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
63
Final Class (Contd.)
public final class Mobile {
String mobileMakerName, modelName;
int price;
public Mobile(String mobileMakerName, String
modelName, int price) {
this.mobileMakerName = mobileMakerName;
this.modelName = modelName;
this.price = price;
}
}
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
64
Final Class (Contd.)
public String getMobileMakerName() {
return mobileMakerName;
}
public void setMobileMakerName(String mobileMakerName) {
this.mobileMakerName = mobileMakerName;
}
public String getModelName() {
return modelName;
}
public void setModelName(String modelName) {
this.modelName = modelName;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
}
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
65
Final Class (Contd.)
• In the preceding code a final class Mobile is created.
• Consider the following code:
class MobileTest extends Mobile{
}
• The preceding code, will generate a compile time error as the Mobile
class can not be sub classed.
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
66
Final Method
• A final method is defined using the final keyword.
• A method which should not be overridden by its sub class are defined
as final method.
• The syntax to define final method:
<accessmodifier> final
<returntype><methodname>(parameterlist){
}
• An example to define final method:
final void displayShape(String shapeName){
System.out.println("Shape Name="+shapeName);
}
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
67
Final Method (Contd.)
• An example to work with final method:
public abstract class Shape
{
public static float pi = 3.142f;
protected float height;
protected float width;
abstract float area() ;
final void displayShape(String shapeName){
System.out.println("Shape Name="+shapeName);
}
}
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
68
Final Method (Contd.)
public class Square extends Shape{
Square(float h, float w)
{
height = h;
width = w;
}
float area()
{
return height * width;
}
}
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
69
Final Method (Contd.)
public class Rectangle extends Shape
{
Rectangle(float h, float w)
{
height = h;
width = w;
}
float area()
{
return height * width;
}
}
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
70
Final Method (Contd.)
public class Circle extends Shape
{
float radius;
Circle(float r)
{
radius = r;
}
float area()
{
return Shape.pi * radius *radius;
}
} © People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
71
Final Method (Contd.)
class FinalMethodDemo
{
public static void main(String args[])
{
Square sObj = new Square(5,5);
Rectangle rObj = new Rectangle(5,7);
Circle cObj = new Circle(2);
sObj.displayShape("Square");
System.out.println("Area: " + sObj.area());
rObj.displayShape("Rectangle");
System.out.println("Area: " + rObj.area());
rObj.displayShape("Circle");
System.out.println("Area: " + cObj.area());
}
}
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
72
Final Method (Contd.)
• In the preceding code, if the sub classes, Square, Rectangle, or Circle
try to override the displayShape() method compile time error will be
raised.
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
73
Final Variables
• A final variables are defined using the final keyword.
• The final variables can not be reinitialized.
• The syntax to create final variable:
final <data type> <variable name>=<value>;
• An example to create final variable:
final int maxValue=100;
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
74
Interface
• An interface is a group of related methods with empty bodies.
• An interface is declared using interface keyword.
• The variable inside interface are by default public, static and final.
• The methods inside interface are by default public and abstract.
• The syntax to define an interface:
<access modifier> interface <interface name>{
}
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
75
Interface
• An example to define an interface:
public interface Printable {
}
• A class can implement an interface and it can implement any number
of interfaces.
• The class that implements an interface should override all the
abstract methods declared inside the interface.
• The syntax to implement an interface:
class <class name> implements <interface name>
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
76
Interface (Contd.)
• An example to implement an interface:
class A4Paper implements Printable{
}
• An interface can extend one or more interfaces.
• A class can extend another class and implement one or more
interfaces.
• The class that implements the interface should override all the
abstract methods of the interface.
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
77
Interface (Contd.)
• An example to work with interface:
public interface Printable {
public void print();
}
public class A4Paper implements Printable{
public void print(){
System.out.println("A4Paper Print");
}
}
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
78
Interface (Contd.)
public class A6Paper implements Printable{
public void print(){
System.out.println("A6Paper Print");
}
}
public class InterfaceDemo {
public static void main(String args[]){
A4Paper obj1=new A4Paper();
A6Paper obj2=new A6Paper();
obj1.print();
obj2.print();
}
}
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
79
Interface (Contd.)
• The preceding code output will be:
A4Paper Print
A6Paper Print
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
80
Abstract Class vs Interface
• Java provides and supports the creation of abstract classes and
interfaces. Both implementations share some common features, but
they differ in the following features:
• All methods in an interface are implicitly abstract. On the other hand, an
abstract class may contain both abstract and non-abstract methods.
• A class may implement a number of Interfaces, but can extend only one
abstract class.
• In order for a class to implement an interface, it must implement all its
declared methods. However, a class may not implement all declared methods
of an abstract class. Though, in this case, the sub-class must also be declared
as abstract.
• Abstract classes can implement interfaces without even providing the
implementation of interface methods.
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
81
Abstract Class vs Interface (Contd.)
• Variables declared in a Java interface is by default final. An abstract class may
contain non-final variables.
• Members of a Java interface are public by default. A member of an abstract
class can either be private, protected or public.
• An interface is absolutely abstract and cannot be instantiated. An abstract
class also cannot be instantiated, but can be invoked if it contains a main
method.
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
82
Summary
• In this topic, you have learnt that:
• In Java, the classes can be derived from other classes.
• The derived class can inherit the fields and methods of base class.
• A class that is derived from another class is called a subclass.
• Java supports single, multilevel, and hierarchical inheritance.
• The super keyword is used to refer an instance of immediate parent class
object.
• Overriding is feature that enables a sub class to redefine a super class
method.
• Variables and methods that have the static modifier are called static variables
and methods.
• A single copy static variable is shared by all instances of the class.
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
83
Summary (Contd.)
• The code in static blocks is executed when the class is loaded by JVM.
• Static import allows to import static members of class and use them, as they
are declared in the same class.
• Abstract classes cannot be instantiated, but they can be sub classed.
• A class that should not be sub classed should created as a final class.
• A method which should not be overridden by its sub class are defined as final
method.
• An interface is a group of related methods with empty bodies.
© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
84

Java Day-3

  • 1.
    © People Strategists- Duplication is strictly prohibited - www.peoplestrategists.com 1
  • 2.
    Day 3 Inheritance Advance ClassFeatures Abstraction © People Strategists - Duplication is strictly prohibited - www.peoplestrategists.com 2
  • 3.
    Inheritance © People Strategists- Duplication is strictly prohibited - www.peoplestrategists.com 3
  • 4.
    Inheritance Basic • InJava, the classes can be derived from other classes. • The derived class can inherit the fields and methods of base class. • A class that is derived from another class is called a subclass. • The class from which the subclass is derived is called as superclass. • The syntax to derive a class: class <classname> extends <superclassname> © People Strategists - Duplication is strictly prohibited - www.peoplestrategists.com 4
  • 5.
    Inheritance Basic (Contd.) •An example to derive a class: class Base{ } class Sub extends Base{ } • In the preceding code snippet, Base is the super class and Sub is the sub class. • Java supports following types of inheritance: • Single inheritance • Multilevel inheritance • Hierarchical inheritance © People Strategists - Duplication is strictly prohibited - www.peoplestrategists.com 5
  • 6.
    Inheritance Basic (Contd.) ClassA Class B Class A Class B Class C Class A Class B Class D Class E Class C Class F Single Inheritance Multilevel Inheritance Hierarchical Inheritance © People Strategists - Duplication is strictly prohibited - www.peoplestrategists.com 6
  • 7.
    Inheritance Basic (Contd.) •An example to implement single inheritance: public class Base { int baseA; Base(){ baseA=20; } void printBase(){ System.out.println("baseA value="+baseA); } } © People Strategists - Duplication is strictly prohibited - www.peoplestrategists.com 7
  • 8.
    Inheritance Basic (Contd.) publicclass Sub extends Base{ int subA; Sub(){ subA=67; } void printSub(){ System.out.println("baseA value="+baseA); System.out.println("subA value="+subA); } } © People Strategists - Duplication is strictly prohibited - www.peoplestrategists.com 8
  • 9.
    Inheritance Basic (Contd.) publicclass InheritanceDemo { public static void main(String args[]){ Sub obj=new Sub(); obj.printSub(); obj.printBase(); } } • The preceding code output will be: baseA value=20 subA value=67 baseA value=20 © People Strategists - Duplication is strictly prohibited - www.peoplestrategists.com 9
  • 10.
    Inheritance Basic (Contd.) •In the preceding code, the base class object is not created. However, from the output you can notice that base class constructor was invoked. • When a sub class object is created the sub class constructor is invoked. From the sub class constructor the JVM internally invokes the super class constructor. • You can also notice that the sub class objects are able to access the super class members. © People Strategists - Duplication is strictly prohibited - www.peoplestrategists.com 10
  • 11.
    Inheritance Basic (Contd.) •An example to implement multilevel inheritance: public class Circle { double radius; public Circle() { radius = 1.0; } public Circle(double r) { radius = r; } public double getRadius() { return radius; } public double getArea() { return radius*radius*3.14; } } © People Strategists - Duplication is strictly prohibited - www.peoplestrategists.com 11
  • 12.
    Inheritance Basic (Contd.) publicclass Cylinder extends Circle { private double height; public Cylinder() { height = 1.0; } public Cylinder(double r, double h) { setRadius(r); height = h; } public double getHeight() { return height; } public void setHeight(double height) { this.height = height; } public double getVolume() { return getArea()*height; } } © People Strategists - Duplication is strictly prohibited - www.peoplestrategists.com 12
  • 13.
    Inheritance Basic (Contd.) publicclass InheritanceDemo { public static void main(String args[]){ Cylinder cy1 = new Cylinder(); System.out.println("Radius is " + cy1.getRadius() + " Height is " + cy1.getHeight() + " Base area is " + cy1.getArea() + " Volume is " + cy1.getVolume()); Cylinder cy2 = new Cylinder(5.0, 2.0); System.out.println("Radius is " + cy2.getRadius() + " Height is " + cy2.getHeight() + " Base area is " + cy2.getArea() + " Volume is " + cy2.getVolume()); } } © People Strategists - Duplication is strictly prohibited - www.peoplestrategists.com 13
  • 14.
    Inheritance Basic (Contd.) •The preceding code output will be: Radius is 1.0 Height is 1.0 Base area is 3.14 Volume is 3.14 Radius is 5.0 Height is 2.0 Base area is 78.5 Volume is 157.0 © People Strategists - Duplication is strictly prohibited - www.peoplestrategists.com 14
  • 15.
    Inheritance Basic (Contd.) •An example to implement hierarchical inheritance: public class Shapes { int noOfSides; void display(){ System.out.println("No of sides:"+noOfSides); } } © People Strategists - Duplication is strictly prohibited - www.peoplestrategists.com 15
  • 16.
    Inheritance Basic (Contd.) publicclass Rectangle extends Shapes { Rectangle(){ noOfSides=4; } } © People Strategists - Duplication is strictly prohibited - www.peoplestrategists.com 16
  • 17.
    Inheritance Basic (Contd.) publicclass Pentagon extends Shapes { public Pentagon() { noOfSides=5; } } © People Strategists - Duplication is strictly prohibited - www.peoplestrategists.com 17
  • 18.
    Inheritance Basic (Contd.) publicclass Hexagon extends Shapes { public Hexagon() { noOfSides=6; } } © People Strategists - Duplication is strictly prohibited - www.peoplestrategists.com 18
  • 19.
    Inheritance Basic (Contd.) publicclass InheritanceDemo { public static void main(String args[]){ Shapes sObj=new Shapes(); Rectangle rObj =new Rectangle(); Pentagon pObj=new Pentagon(); Hexagon hObj=new Hexagon(); sObj.display(); rObj.display(); pObj.display(); hObj.display(); } } © People Strategists - Duplication is strictly prohibited - www.peoplestrategists.com 19
  • 20.
    Inheritance Basic (Contd.) •The output of the preceding code will be: No of sides:0 No of sides:4 No of sides:5 No of sides:6 © People Strategists - Duplication is strictly prohibited - www.peoplestrategists.com 20
  • 21.
    Inheritance Basic (Contd.) •Consider the following code snippet: class Shapes { int noOfSides; void displayShapes(){ System.out.println("No of sides:"+noOfSides); } } class Rectangle extends Shapes { Rectangle(){ noOfSides=4; } void displayRectangle(){ System.out.println("Rectangle"); } } © People Strategists - Duplication is strictly prohibited - www.peoplestrategists.com 21
  • 22.
    Inheritance Basic (Contd.) publicclass InheritanceDemo { public static void main(String args[]){ Shapes sObj=new Rectangle(); sObj.displayShapes(); } } • In the preceding code, the reference variable sObj, refers to the object of Rectangle class. Therefore, the sObj.displayShapes();statement will raise a compilation error. © People Strategists - Duplication is strictly prohibited - www.peoplestrategists.com 22
  • 23.
    Use of superKeyword • The super keyword is used to refer an instance of immediate parent class object. • An example to work with super keyword: public class Base { int val; Base(){ val=20; } void printBase(){ System.out.println("Value="+val); } } © People Strategists - Duplication is strictly prohibited - www.peoplestrategists.com 23
  • 24.
    Use of superKeyword (Contd.) public class Sub extends Base{ int val; Sub(){ val=67; } void printSub(){ System.out.println("Base class Value="+super.val); System.out.println("Sub class value="+val); } } © People Strategists - Duplication is strictly prohibited - www.peoplestrategists.com 24
  • 25.
    Use of superKeyword (Contd.) public class InheritanceDemo { public static void main(String args[]){ Sub sObj=new Sub(); sObj.printBase(); sObj.printSub(); } } • The preceding code output will be: Value=20 Base class Value=20 Sub class value=67 © People Strategists - Duplication is strictly prohibited - www.peoplestrategists.com 25
  • 26.
    Use of superKeyword (Contd.) • When a sub class constructor does not explicitly calls the super class constructor, then the compiler will insert a super() statement. • This statements invokes the super class constructor without parameter. • Consider the following code: class Base{ int baseX; Base(){ this(10); System.out.println("Base()"); } © People Strategists - Duplication is strictly prohibited - www.peoplestrategists.com 26
  • 27.
    Use of superKeyword (Contd.) Base(int x){ baseX=x; System.out.println("Base(int)"); } } © People Strategists - Duplication is strictly prohibited - www.peoplestrategists.com 27
  • 28.
    Use of superKeyword (Contd.) class Sub extends Base{ int subX; Sub(){ subX=20; System.out.println("Sub()"); } } public class SuperDemo { public static void main(String args[]){ Sub sObj=new Sub(); } } © People Strategists - Duplication is strictly prohibited - www.peoplestrategists.com 28
  • 29.
    Use of superKeyword (Contd.) • The preceding code output will be: Base(int) Base() Sub() • Now, in the preceding code if you remove the Base(){} constructor definition, an compilation error will be raised in the Sub(){} constructor definition. • To rectify this error, the Base class constructor should be explicitly called from Sub class constructor. This can be achieved by adding the following code snippet to the Sub() constructor: super(7); © People Strategists - Duplication is strictly prohibited - www.peoplestrategists.com 29
  • 30.
    Use of superKeyword (Contd.) • The super() statement must be the first statementinside the sub class constructor. © People Strategists - Duplication is strictly prohibited - www.peoplestrategists.com 30
  • 31.
    Overriding • Overriding isfeature that enables a sub class to redefine a super class method. • The overriding method has the same name, number and type of parameters, and return type as the method that it overrides. • In Java, runtime polymorphism is achieved through overriding. • Runtime polymorphism means that the exact method that is bound to the object is not known at compile time. © People Strategists - Duplication is strictly prohibited - www.peoplestrategists.com 31
  • 32.
    Overriding (Contd.) • Anexample to work with overridden methods: public class Base { int val; Base(){ val=20; } void display(){ System.out.println("Value="+val); } } © People Strategists - Duplication is strictly prohibited - www.peoplestrategists.com 32
  • 33.
    Overriding (Contd.) public classSub extends Base{ int val; Sub(){ val=67; } void display(){ System.out.println("Base class Value="+super.val); System.out.println("Sub class value="+val); } } © People Strategists - Duplication is strictly prohibited - www.peoplestrategists.com 33
  • 34.
    Overriding (Contd.) public classInheritanceDemo { public static void main(String args[]){ Base bObj=new Base(); Sub sObj=new Sub(); bObj.display(); sObj.display(); } • The preceding code output will be: Value=20 Base class Value=20 Sub class value=67 © People Strategists - Duplication is strictly prohibited - www.peoplestrategists.com 34
  • 35.
    Overriding (Contd.) • Considerthe following code snippet: class Shapes { int noOfSides; public void displayShapes(){ System.out.println("No of sides:"+noOfSides); } } class Rectangle extends Shapes { Rectangle(){ noOfSides=4; } © People Strategists - Duplication is strictly prohibited - www.peoplestrategists.com 35
  • 36.
    Overriding (Contd.) void displayShapes(){ System.out.println("Rectangle"); } } •The preceding code will generate a compilation error, because the base class method displayShape() access control level is more than the overridden method. • The following code is a valid overridden method example : class Shapes { int noOfSides; void displayShapes(){ System.out.println("No of sides:"+noOfSides); } } © People Strategists - Duplication is strictly prohibited - www.peoplestrategists.com 36
  • 37.
    Overriding (Contd.) class Rectangleextends Shapes { Rectangle(){ noOfSides=4; } public void displayShapes(){ System.out.println("Rectangle"); } } © People Strategists - Duplication is strictly prohibited - www.peoplestrategists.com 37
  • 38.
    Overriding (Contd.) • Considerthe following code: class Shapes { int noOfSides; void displayShapes(){ System.out.println("No of sides:"+noOfSides); } } class Rectangle extends Shapes { Rectangle(){ noOfSides=4; } © People Strategists - Duplication is strictly prohibited - www.peoplestrategists.com 38
  • 39.
    Overriding (Contd.) void displayShapes(){ System.out.println("Rectangle"); } } publicclass InheritanceDemo { public static void main(String args[]){ Shapes sObj=new Rectangle(); sObj.displayShapes(); } } © People Strategists - Duplication is strictly prohibited - www.peoplestrategists.com 39
  • 40.
    Overriding (Contd.) • Thepreceding code output will be: Rectangle • The behavior demonstrated in the preceding code is referred as virtual method invocation. • The JVM calls the appropriate method for the object that is referred by the reference variable. © People Strategists - Duplication is strictly prohibited - www.peoplestrategists.com 40
  • 41.
    Advance Class Features ©People Strategists - Duplication is strictly prohibited - www.peoplestrategists.com 41
  • 42.
    Static Variables • Variablesthat have the static modifier are called static variables or class variables. • Static variable belongs to the class and not to object. • A single copy static variable is shared by all instances of the class. • A static variable can be accessed outside the class by using the class name. • The syntax to access a static variable: <classname>.<staticvariablename> © People Strategists - Duplication is strictly prohibited - www.peoplestrategists.com 42
  • 43.
    Static Variables (Contd.) •An example to work with static variable: public class StaticVarDemo { static int count; StaticVarDemo(){ count++; } void display(){ System.out.println("The count="+count); } © People Strategists - Duplication is strictly prohibited - www.peoplestrategists.com 43
  • 44.
    Static Variables (Contd.) publicstatic void main(String args[]){ StaticVarDemo obj1=new StaticVarDemo(); obj1.display(); StaticVarDemo obj2=new StaticVarDemo(); obj2.display(); obj1.display(); } } • The preceding code output will be: The count=1 The count=2 The count=2 © People Strategists - Duplication is strictly prohibited - www.peoplestrategists.com 44
  • 45.
    Static Methods • Methodsthat have the static modifier are called static methods. • Static methods belongs to the class and not to object. • A static method can access only static data. • A static method cannot refer to this or super keywords. • A static method can be overloaded. However, they can not be overridden. • A static method can be accessed outside the class by using the class name. © People Strategists - Duplication is strictly prohibited - www.peoplestrategists.com 45
  • 46.
    Static Methods (Contd.) •The syntax to access a static method: <classname>.<methodname> • Example: class Test{ static void display(){ System.out.println("display()"); } } public class StaticMethodDemo { static void show(){ StaticMethodDemo o=new StaticMethodDemo(); System.out.println("display()"); Test.display(); } } © People Strategists - Duplication is strictly prohibited - www.peoplestrategists.com 46
  • 47.
    Static Methods (Contd.) •An example of to work static method: public class StaticMethodDemo { static void display(){ System.out.println("Static display method"); } public static void main(String args[]) { display(); } } • The preceding code output will be: Static display method © People Strategists - Duplication is strictly prohibited - www.peoplestrategists.com 47
  • 48.
    Static Methods (Contd.) •Consider the following code snippet: void display(){ System.out.println("display()"); } static void show(){ System.out.println("display()"); display(); } • The preceding code snippet will generate a compilation error because a non static method can not be called from a static method. However, you can create an instance of the class and call the non static method using the reference variable. © People Strategists - Duplication is strictly prohibited - www.peoplestrategists.com 48
  • 49.
    Static Block • Astatic block is a block of code enclosed in braces, { }, and preceded by the static keyword. • The code in static blocks is executed when the class is loaded by JVM. • A static block is used to initialize the static variables. © People Strategists - Duplication is strictly prohibited - www.peoplestrategists.com 49
  • 50.
    Static Block (Contd.) •An example to work with static block: public class StaticBlockDemo { static int val; static { val=10; } StaticBlockDemo(){ val++; } void display(){ System.out.println("Value="+val); } © People Strategists - Duplication is strictly prohibited - www.peoplestrategists.com 50
  • 51.
    Static Block (Contd.) publicstatic void main(String args[]){ StaticBlockDemo obj=new StaticBlockDemo(); obj.display(); } } • The preceding code output will be: Value=11 © People Strategists - Duplication is strictly prohibited - www.peoplestrategists.com 51
  • 52.
    Static Import • Staticimport allows to import static members of class and use them, as they are declared in the same class. • The syntax for static import: import static <packagename>.<classname>.*; • An example for static import: import static java.lang.Math.*; © People Strategists - Duplication is strictly prohibited - www.peoplestrategists.com 52
  • 53.
    Static Import (Contd.) •An example to work with static import: import static java.lang.Math.*; public class StaticImportDemo { public static void main(String args[]) { double circleArea=PI*pow(4, 2); System.out.println("Area of circle:"+circleArea); } } • The preceding code output will be: Area of circle:50.26548245743669 © People Strategists - Duplication is strictly prohibited - www.peoplestrategists.com 53
  • 54.
    Abstraction © People Strategists- Duplication is strictly prohibited - www.peoplestrategists.com 54
  • 55.
    Abstract Class • Anabstract class is a class that is declared abstract. • Abstract classes cannot be instantiated, but they can be sub classed. • The syntax to define abstract class: <accessmodifier> abstract class <classname>{ } • An example to define abstract class: abstract class Instrument { ………. } © People Strategists - Duplication is strictly prohibited - www.peoplestrategists.com 55
  • 56.
    Abstract Method • Anabstract method is a method that is declared without an implementation. • The syntax to declare an abstract method: <accessmodifier> abstract <returntype><methodname>(parameterlist); • An example to declare an abstract method: abstract public void play(); © People Strategists - Duplication is strictly prohibited - www.peoplestrategists.com 56
  • 57.
    Abstract Class andMethod (Contd.) • An example to work with abstract class and method: abstract class Instrument { protected String name; abstract public void play(); } abstract class StringedInstrument extends Instrument { protected int numberOfStrings; } public class ElectricGuitar extends StringedInstrument { public ElectricGuitar() { super(); this.name = "Guitar"; this.numberOfStrings = 6; } © People Strategists - Duplication is strictly prohibited - www.peoplestrategists.com 57
  • 58.
    Abstract Class andMethod (Contd.) public class ElectricGuitar extends StringedInstrument { public ElectricGuitar() { super(); this.name = "Guitar"; this.numberOfStrings = 6; } public ElectricGuitar(int numberOfStrings) { super(); this.name = "Guitar"; this.numberOfStrings = numberOfStrings; } public void play() { System.out.println("An electric " + numberOfStrings + "-string " + name + " is rocking!"); } } © People Strategists - Duplication is strictly prohibited - www.peoplestrategists.com 58
  • 59.
    Abstract Class andMethod (Contd.) public class ElectricBassGuitar extends StringedInstrument { public ElectricBassGuitar() { super(); this.name = "Bass Guitar"; this.numberOfStrings = 4; } public ElectricBassGuitar(int numberOfStrings) { super(); this.name = "Bass Guitar"; this.numberOfStrings = numberOfStrings; } public void play() { System.out.println("An electric " + numberOfStrings + "-string " + name + " is rocking!"); } } © People Strategists - Duplication is strictly prohibited - www.peoplestrategists.com 59
  • 60.
    Abstract Class andMethod (Contd.) public class Execution { public static void main(String[] args) { ElectricGuitar guitar = new ElectricGuitar(); ElectricBassGuitar bassGuitar = new ElectricBassGuitar(); guitar.play(); bassGuitar.play(); guitar = new ElectricGuitar(7); bassGuitar = new ElectricBassGuitar(5); guitar.play(); bassGuitar.play(); } } © People Strategists - Duplication is strictly prohibited - www.peoplestrategists.com 60
  • 61.
    Abstract Class andMethod (Contd.) • The preceding code output will be: An electric 6-string Guitar is rocking! An electric 4-string Bass Guitar is rocking! An electric 7-string Guitar is rocking! An electric 5-string Bass Guitar is rocking! © People Strategists - Duplication is strictly prohibited - www.peoplestrategists.com 61
  • 62.
    Abstract Class andMethod (Contd.) • An abstract class can have abstract and/or non abstract methods. • An abstract method can be declared only inside an abstract class or an interface. • An abstract class can extend another abstract class. • When an abstract class extends another abstract class, it may or may not override the abstract methods of the abstract base class. • However, when a non abstract sub class inherits an abstract class, then the sub class must override all the abstract methods. © People Strategists - Duplication is strictly prohibited - www.peoplestrategists.com 62
  • 63.
    Final Class • Finalclass is class defined with final keyword. • If a class should not be sub classed then a final class should be created. • The syntax to define a final class: <access modifier> final class <class name>{ } • An example to define a final class: public final class Mobile { } © People Strategists - Duplication is strictly prohibited - www.peoplestrategists.com 63
  • 64.
    Final Class (Contd.) publicfinal class Mobile { String mobileMakerName, modelName; int price; public Mobile(String mobileMakerName, String modelName, int price) { this.mobileMakerName = mobileMakerName; this.modelName = modelName; this.price = price; } } © People Strategists - Duplication is strictly prohibited - www.peoplestrategists.com 64
  • 65.
    Final Class (Contd.) publicString getMobileMakerName() { return mobileMakerName; } public void setMobileMakerName(String mobileMakerName) { this.mobileMakerName = mobileMakerName; } public String getModelName() { return modelName; } public void setModelName(String modelName) { this.modelName = modelName; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } } © People Strategists - Duplication is strictly prohibited - www.peoplestrategists.com 65
  • 66.
    Final Class (Contd.) •In the preceding code a final class Mobile is created. • Consider the following code: class MobileTest extends Mobile{ } • The preceding code, will generate a compile time error as the Mobile class can not be sub classed. © People Strategists - Duplication is strictly prohibited - www.peoplestrategists.com 66
  • 67.
    Final Method • Afinal method is defined using the final keyword. • A method which should not be overridden by its sub class are defined as final method. • The syntax to define final method: <accessmodifier> final <returntype><methodname>(parameterlist){ } • An example to define final method: final void displayShape(String shapeName){ System.out.println("Shape Name="+shapeName); } © People Strategists - Duplication is strictly prohibited - www.peoplestrategists.com 67
  • 68.
    Final Method (Contd.) •An example to work with final method: public abstract class Shape { public static float pi = 3.142f; protected float height; protected float width; abstract float area() ; final void displayShape(String shapeName){ System.out.println("Shape Name="+shapeName); } } © People Strategists - Duplication is strictly prohibited - www.peoplestrategists.com 68
  • 69.
    Final Method (Contd.) publicclass Square extends Shape{ Square(float h, float w) { height = h; width = w; } float area() { return height * width; } } © People Strategists - Duplication is strictly prohibited - www.peoplestrategists.com 69
  • 70.
    Final Method (Contd.) publicclass Rectangle extends Shape { Rectangle(float h, float w) { height = h; width = w; } float area() { return height * width; } } © People Strategists - Duplication is strictly prohibited - www.peoplestrategists.com 70
  • 71.
    Final Method (Contd.) publicclass Circle extends Shape { float radius; Circle(float r) { radius = r; } float area() { return Shape.pi * radius *radius; } } © People Strategists - Duplication is strictly prohibited - www.peoplestrategists.com 71
  • 72.
    Final Method (Contd.) classFinalMethodDemo { public static void main(String args[]) { Square sObj = new Square(5,5); Rectangle rObj = new Rectangle(5,7); Circle cObj = new Circle(2); sObj.displayShape("Square"); System.out.println("Area: " + sObj.area()); rObj.displayShape("Rectangle"); System.out.println("Area: " + rObj.area()); rObj.displayShape("Circle"); System.out.println("Area: " + cObj.area()); } } © People Strategists - Duplication is strictly prohibited - www.peoplestrategists.com 72
  • 73.
    Final Method (Contd.) •In the preceding code, if the sub classes, Square, Rectangle, or Circle try to override the displayShape() method compile time error will be raised. © People Strategists - Duplication is strictly prohibited - www.peoplestrategists.com 73
  • 74.
    Final Variables • Afinal variables are defined using the final keyword. • The final variables can not be reinitialized. • The syntax to create final variable: final <data type> <variable name>=<value>; • An example to create final variable: final int maxValue=100; © People Strategists - Duplication is strictly prohibited - www.peoplestrategists.com 74
  • 75.
    Interface • An interfaceis a group of related methods with empty bodies. • An interface is declared using interface keyword. • The variable inside interface are by default public, static and final. • The methods inside interface are by default public and abstract. • The syntax to define an interface: <access modifier> interface <interface name>{ } © People Strategists - Duplication is strictly prohibited - www.peoplestrategists.com 75
  • 76.
    Interface • An exampleto define an interface: public interface Printable { } • A class can implement an interface and it can implement any number of interfaces. • The class that implements an interface should override all the abstract methods declared inside the interface. • The syntax to implement an interface: class <class name> implements <interface name> © People Strategists - Duplication is strictly prohibited - www.peoplestrategists.com 76
  • 77.
    Interface (Contd.) • Anexample to implement an interface: class A4Paper implements Printable{ } • An interface can extend one or more interfaces. • A class can extend another class and implement one or more interfaces. • The class that implements the interface should override all the abstract methods of the interface. © People Strategists - Duplication is strictly prohibited - www.peoplestrategists.com 77
  • 78.
    Interface (Contd.) • Anexample to work with interface: public interface Printable { public void print(); } public class A4Paper implements Printable{ public void print(){ System.out.println("A4Paper Print"); } } © People Strategists - Duplication is strictly prohibited - www.peoplestrategists.com 78
  • 79.
    Interface (Contd.) public classA6Paper implements Printable{ public void print(){ System.out.println("A6Paper Print"); } } public class InterfaceDemo { public static void main(String args[]){ A4Paper obj1=new A4Paper(); A6Paper obj2=new A6Paper(); obj1.print(); obj2.print(); } } © People Strategists - Duplication is strictly prohibited - www.peoplestrategists.com 79
  • 80.
    Interface (Contd.) • Thepreceding code output will be: A4Paper Print A6Paper Print © People Strategists - Duplication is strictly prohibited - www.peoplestrategists.com 80
  • 81.
    Abstract Class vsInterface • Java provides and supports the creation of abstract classes and interfaces. Both implementations share some common features, but they differ in the following features: • All methods in an interface are implicitly abstract. On the other hand, an abstract class may contain both abstract and non-abstract methods. • A class may implement a number of Interfaces, but can extend only one abstract class. • In order for a class to implement an interface, it must implement all its declared methods. However, a class may not implement all declared methods of an abstract class. Though, in this case, the sub-class must also be declared as abstract. • Abstract classes can implement interfaces without even providing the implementation of interface methods. © People Strategists - Duplication is strictly prohibited - www.peoplestrategists.com 81
  • 82.
    Abstract Class vsInterface (Contd.) • Variables declared in a Java interface is by default final. An abstract class may contain non-final variables. • Members of a Java interface are public by default. A member of an abstract class can either be private, protected or public. • An interface is absolutely abstract and cannot be instantiated. An abstract class also cannot be instantiated, but can be invoked if it contains a main method. © People Strategists - Duplication is strictly prohibited - www.peoplestrategists.com 82
  • 83.
    Summary • In thistopic, you have learnt that: • In Java, the classes can be derived from other classes. • The derived class can inherit the fields and methods of base class. • A class that is derived from another class is called a subclass. • Java supports single, multilevel, and hierarchical inheritance. • The super keyword is used to refer an instance of immediate parent class object. • Overriding is feature that enables a sub class to redefine a super class method. • Variables and methods that have the static modifier are called static variables and methods. • A single copy static variable is shared by all instances of the class. © People Strategists - Duplication is strictly prohibited - www.peoplestrategists.com 83
  • 84.
    Summary (Contd.) • Thecode in static blocks is executed when the class is loaded by JVM. • Static import allows to import static members of class and use them, as they are declared in the same class. • Abstract classes cannot be instantiated, but they can be sub classed. • A class that should not be sub classed should created as a final class. • A method which should not be overridden by its sub class are defined as final method. • An interface is a group of related methods with empty bodies. © People Strategists - Duplication is strictly prohibited - www.peoplestrategists.com 84