Java Day-3

84
© People Strategists - Duplication is strictly prohibited - www.peoplestrategists.com 1

Transcript of Java Day-3

© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com

1

Day 3Inheritance

Advance Class FeaturesAbstraction

© 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 thesub 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=20subA value=67baseA 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 wasinvoked.

• When a sub class object is created the sub class constructor isinvoked. From the sub class constructor the JVM internally invokesthe super class constructor.

• You can also notice that the sub class objects are able to access thesuper 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 Volumeis 3.14Radius is 5.0 Height is 2.0 Base area is 78.5 Volumeis 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:0No of sides:4No of sides:5No 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 theobject of Rectangle class. Therefore, thesObj.displayShapes();statement will raise a compilationerror.

© 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 classobject.

• 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 classValue="+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=20Base class Value=20Sub 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 classconstructor, 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(){} constructordefinition, an compilation error will be raised in the Sub(){}constructor definition.

• To rectify this error, the Base class constructor should be explicitlycalled from Sub class constructor. This can be achieved by adding thefollowing 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 classconstructor.

© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 30

Overriding

• Overriding is feature that enables a sub class to redefine a super classmethod.

• The overriding method has the same name, number and type ofparameters, 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 classValue="+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=20Base class Value=20Sub 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 thebase class method displayShape() access control level is more thanthe 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 referredas virtual method invocation.

• The JVM calls the appropriate method for the object that isreferred 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 orclass 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=1The count=2The 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 becausea 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 methodusing 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 precededby 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 animplementation.

• 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, StringmodelName, 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 Mobileclass 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 Circletry to override the displayShape() method compile time error will beraised.

© 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 numberof interfaces.

• The class that implements an interface should override all theabstract 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 PrintA6Paper Print

© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com 80

Abstract Class vs Interface

• Java provides and supports the creation of abstract classes andinterfaces. Both implementations share some common features, butthey differ in the following features:

• All methods in an interface are implicitly abstract. On the other hand, anabstract class may contain both abstract and non-abstract methods.

• A class may implement a number of Interfaces, but can extend only oneabstract class.

• In order for a class to implement an interface, it must implement all itsdeclared methods. However, a class may not implement all declared methodsof an abstract class. Though, in this case, the sub-class must also be declaredas abstract.

• Abstract classes can implement interfaces without even providing theimplementation 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 maycontain non-final variables.

• Members of a Java interface are public by default. A member of an abstractclass can either be private, protected or public.

• An interface is absolutely abstract and cannot be instantiated. An abstractclass also cannot be instantiated, but can be invoked if it contains a mainmethod.

© 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