SlideShare a Scribd company logo
© 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

More Related Content

What's hot

Java Programming - 05 access control in java
Java Programming - 05 access control in javaJava Programming - 05 access control in java
Java Programming - 05 access control in java
Danairat Thanabodithammachari
 
Java oop
Java oopJava oop
Java oop
bchinnaiyan
 
Session 08 - OOP with Java - continued
Session 08 - OOP with Java - continuedSession 08 - OOP with Java - continued
Session 08 - OOP with Java - continued
PawanMM
 
Core java Essentials
Core java EssentialsCore java Essentials
Java Day-4
Java Day-4Java Day-4
Java Day-4
People Strategists
 
Java Day-5
Java Day-5Java Day-5
Java Day-5
People Strategists
 
Collection Framework in Java | Generics | Input-Output in Java | Serializatio...
Collection Framework in Java | Generics | Input-Output in Java | Serializatio...Collection Framework in Java | Generics | Input-Output in Java | Serializatio...
Collection Framework in Java | Generics | Input-Output in Java | Serializatio...
Sagar Verma
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorials
FALLEE31188
 
Object Oriented Programming in PHP
Object Oriented Programming in PHPObject Oriented Programming in PHP
Object Oriented Programming in PHP
Lorna Mitchell
 
OOP with Java - Part 3
OOP with Java - Part 3OOP with Java - Part 3
OOP with Java - Part 3
Hitesh-Java
 
Java OOP Programming language (Part 4) - Collection
Java OOP Programming language (Part 4) - CollectionJava OOP Programming language (Part 4) - Collection
Java OOP Programming language (Part 4) - Collection
OUM SAOKOSAL
 
Inheritance
InheritanceInheritance
Inheritance
piyush Kumar Sharma
 
Core Java Concepts
Core Java ConceptsCore Java Concepts
Core Java Concepts
mdfkhan625
 
05 Java Language And OOP Part V
05 Java Language And OOP Part V05 Java Language And OOP Part V
05 Java Language And OOP Part V
Hari Christian
 
iOS Basic
iOS BasiciOS Basic
iOS Basic
Duy Do Phan
 
03 Java Language And OOP Part III
03 Java Language And OOP Part III03 Java Language And OOP Part III
03 Java Language And OOP Part III
Hari Christian
 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
rajveer_Pannu
 
Java
Java Java
Classes in c++ (OOP Presentation)
Classes in c++ (OOP Presentation)Classes in c++ (OOP Presentation)
Classes in c++ (OOP Presentation)
Majid Saeed
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorials
Mayank Jain
 

What's hot (20)

Java Programming - 05 access control in java
Java Programming - 05 access control in javaJava Programming - 05 access control in java
Java Programming - 05 access control in java
 
Java oop
Java oopJava oop
Java oop
 
Session 08 - OOP with Java - continued
Session 08 - OOP with Java - continuedSession 08 - OOP with Java - continued
Session 08 - OOP with Java - continued
 
Core java Essentials
Core java EssentialsCore java Essentials
Core java Essentials
 
Java Day-4
Java Day-4Java Day-4
Java Day-4
 
Java Day-5
Java Day-5Java Day-5
Java Day-5
 
Collection Framework in Java | Generics | Input-Output in Java | Serializatio...
Collection Framework in Java | Generics | Input-Output in Java | Serializatio...Collection Framework in Java | Generics | Input-Output in Java | Serializatio...
Collection Framework in Java | Generics | Input-Output in Java | Serializatio...
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorials
 
Object Oriented Programming in PHP
Object Oriented Programming in PHPObject Oriented Programming in PHP
Object Oriented Programming in PHP
 
OOP with Java - Part 3
OOP with Java - Part 3OOP with Java - Part 3
OOP with Java - Part 3
 
Java OOP Programming language (Part 4) - Collection
Java OOP Programming language (Part 4) - CollectionJava OOP Programming language (Part 4) - Collection
Java OOP Programming language (Part 4) - Collection
 
Inheritance
InheritanceInheritance
Inheritance
 
Core Java Concepts
Core Java ConceptsCore Java Concepts
Core Java Concepts
 
05 Java Language And OOP Part V
05 Java Language And OOP Part V05 Java Language And OOP Part V
05 Java Language And OOP Part V
 
iOS Basic
iOS BasiciOS Basic
iOS Basic
 
03 Java Language And OOP Part III
03 Java Language And OOP Part III03 Java Language And OOP Part III
03 Java Language And OOP Part III
 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
 
Java
Java Java
Java
 
Classes in c++ (OOP Presentation)
Classes in c++ (OOP Presentation)Classes in c++ (OOP Presentation)
Classes in c++ (OOP Presentation)
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorials
 

Viewers also liked

Inheritance & Polymorphism - 2
Inheritance & Polymorphism - 2Inheritance & Polymorphism - 2
Inheritance & Polymorphism - 2
PRN USM
 
Abstract & Interface
Abstract & InterfaceAbstract & Interface
Abstract & Interface
Linh Lê
 
JSP Technology II
JSP Technology IIJSP Technology II
JSP Technology II
People Strategists
 
How to create a 301 redirect
How to create a 301 redirectHow to create a 301 redirect
How to create a 301 redirect
R K Gupta
 
JSP Standard Tag Library
JSP Standard Tag LibraryJSP Standard Tag Library
JSP Standard Tag Library
Ilio Catallo
 
06 abstract-classes
06 abstract-classes06 abstract-classes
06 abstract-classes
Anup Burange
 
Java Quiz
Java QuizJava Quiz
Java Quiz
Dharmraj Sharma
 
Lecture 5 JSTL, custom tags, maven
Lecture 5   JSTL, custom tags, mavenLecture 5   JSTL, custom tags, maven
Lecture 5 JSTL, custom tags, maven
Fahad Golra
 
Jstl Guide
Jstl GuideJstl Guide
Jstl Guide
Yuval Zilberstein
 
jstl ( jsp standard tag library )
jstl ( jsp standard tag library )jstl ( jsp standard tag library )
jstl ( jsp standard tag library )
Adarsh Patel
 
JSP Standart Tag Lİbrary - JSTL
JSP Standart Tag Lİbrary - JSTLJSP Standart Tag Lİbrary - JSTL
JSP Standart Tag Lİbrary - JSTL
seleciii44
 
Final keyword
Final keywordFinal keyword
Final keyword
Namrata_Thakare
 
Jstl 8
Jstl 8Jstl 8
Jsp lecture
Jsp lectureJsp lecture
8 abstract classes and interfaces
8   abstract classes and interfaces 8   abstract classes and interfaces
8 abstract classes and interfaces
Tuan Ngo
 
Autoboxing And Unboxing In Java
Autoboxing And Unboxing In JavaAutoboxing And Unboxing In Java
Autoboxing And Unboxing In Java
chathuranga kasun bamunusingha
 
Final keyword in java
Final keyword in javaFinal keyword in java
Final keyword in java
Hitesh Kumar
 
Java Server Pages
Java Server PagesJava Server Pages
Java Server Pages
Kasun Madusanke
 
Java interview questions 2
Java interview questions 2Java interview questions 2
Java interview questions 2
Sherihan Anver
 
Jsp element
Jsp elementJsp element
Jsp element
kamal kotecha
 

Viewers also liked (20)

Inheritance & Polymorphism - 2
Inheritance & Polymorphism - 2Inheritance & Polymorphism - 2
Inheritance & Polymorphism - 2
 
Abstract & Interface
Abstract & InterfaceAbstract & Interface
Abstract & Interface
 
JSP Technology II
JSP Technology IIJSP Technology II
JSP Technology II
 
How to create a 301 redirect
How to create a 301 redirectHow to create a 301 redirect
How to create a 301 redirect
 
JSP Standard Tag Library
JSP Standard Tag LibraryJSP Standard Tag Library
JSP Standard Tag Library
 
06 abstract-classes
06 abstract-classes06 abstract-classes
06 abstract-classes
 
Java Quiz
Java QuizJava Quiz
Java Quiz
 
Lecture 5 JSTL, custom tags, maven
Lecture 5   JSTL, custom tags, mavenLecture 5   JSTL, custom tags, maven
Lecture 5 JSTL, custom tags, maven
 
Jstl Guide
Jstl GuideJstl Guide
Jstl Guide
 
jstl ( jsp standard tag library )
jstl ( jsp standard tag library )jstl ( jsp standard tag library )
jstl ( jsp standard tag library )
 
JSP Standart Tag Lİbrary - JSTL
JSP Standart Tag Lİbrary - JSTLJSP Standart Tag Lİbrary - JSTL
JSP Standart Tag Lİbrary - JSTL
 
Final keyword
Final keywordFinal keyword
Final keyword
 
Jstl 8
Jstl 8Jstl 8
Jstl 8
 
Jsp lecture
Jsp lectureJsp lecture
Jsp lecture
 
8 abstract classes and interfaces
8   abstract classes and interfaces 8   abstract classes and interfaces
8 abstract classes and interfaces
 
Autoboxing And Unboxing In Java
Autoboxing And Unboxing In JavaAutoboxing And Unboxing In Java
Autoboxing And Unboxing In Java
 
Final keyword in java
Final keyword in javaFinal keyword in java
Final keyword in java
 
Java Server Pages
Java Server PagesJava Server Pages
Java Server Pages
 
Java interview questions 2
Java interview questions 2Java interview questions 2
Java interview questions 2
 
Jsp element
Jsp elementJsp element
Jsp element
 

Similar to Java Day-3

7 inheritance
7 inheritance7 inheritance
7 inheritance
Abhijit Gaikwad
 
PROGRAMMING IN JAVA
PROGRAMMING IN JAVAPROGRAMMING IN JAVA
PROGRAMMING IN JAVA
SivaSankari36
 
11slide
11slide11slide
11slide
IIUM
 
Java Programming - Inheritance
Java Programming - InheritanceJava Programming - Inheritance
Java Programming - Inheritance
Oum Saokosal
 
JCConf 2020 - New Java Features Released in 2020
JCConf 2020 - New Java Features Released in 2020JCConf 2020 - New Java Features Released in 2020
JCConf 2020 - New Java Features Released in 2020
Joseph Kuo
 
04 Java Language And OOP Part IV
04 Java Language And OOP Part IV04 Java Language And OOP Part IV
04 Java Language And OOP Part IV
Hari Christian
 
11slide.ppt
11slide.ppt11slide.ppt
11slide.ppt
MohammedNouh7
 
C#2
C#2C#2
Constructor
ConstructorConstructor
Constructor
abhay singh
 
Object-oriented Basics
Object-oriented BasicsObject-oriented Basics
Object-oriented Basics
Jamie (Taka) Wang
 
Modern_Java_Workshop manjunath np hj slave
Modern_Java_Workshop manjunath np hj slaveModern_Java_Workshop manjunath np hj slave
Modern_Java_Workshop manjunath np hj slave
gangadharnp111
 
Constructors and Destructors
Constructors and DestructorsConstructors and Destructors
Constructors and Destructors
Keyur Vadodariya
 
pyjamas22_ generic composite in python.pdf
pyjamas22_ generic composite in python.pdfpyjamas22_ generic composite in python.pdf
pyjamas22_ generic composite in python.pdf
Asher Sterkin
 
Java ppt Gandhi Ravi (gandhiri@gmail.com)
Java ppt  Gandhi Ravi  (gandhiri@gmail.com)Java ppt  Gandhi Ravi  (gandhiri@gmail.com)
Java ppt Gandhi Ravi (gandhiri@gmail.com)
Gandhi Ravi
 
Static Analysis in IDEA
Static Analysis in IDEAStatic Analysis in IDEA
Static Analysis in IDEA
HamletDRC
 
Java EE 6 CDI Integrates with Spring & JSF
Java EE 6 CDI Integrates with Spring & JSFJava EE 6 CDI Integrates with Spring & JSF
Java EE 6 CDI Integrates with Spring & JSF
Jiayun Zhou
 
Lego For Engineers - Dependency Injection for LIDNUG (2011-06-03)
Lego For Engineers - Dependency Injection for LIDNUG (2011-06-03)Lego For Engineers - Dependency Injection for LIDNUG (2011-06-03)
Lego For Engineers - Dependency Injection for LIDNUG (2011-06-03)
Theo Jungeblut
 
Learning C++ - Class 4
Learning C++ - Class 4Learning C++ - Class 4
Learning C++ - Class 4
Ali Aminian
 
Native Java with GraalVM
Native Java with GraalVMNative Java with GraalVM
Native Java with GraalVM
Sylvain Wallez
 
Haxe for Flash Platform developer
Haxe for Flash Platform developerHaxe for Flash Platform developer
Haxe for Flash Platform developer
matterhaxe
 

Similar to Java Day-3 (20)

7 inheritance
7 inheritance7 inheritance
7 inheritance
 
PROGRAMMING IN JAVA
PROGRAMMING IN JAVAPROGRAMMING IN JAVA
PROGRAMMING IN JAVA
 
11slide
11slide11slide
11slide
 
Java Programming - Inheritance
Java Programming - InheritanceJava Programming - Inheritance
Java Programming - Inheritance
 
JCConf 2020 - New Java Features Released in 2020
JCConf 2020 - New Java Features Released in 2020JCConf 2020 - New Java Features Released in 2020
JCConf 2020 - New Java Features Released in 2020
 
04 Java Language And OOP Part IV
04 Java Language And OOP Part IV04 Java Language And OOP Part IV
04 Java Language And OOP Part IV
 
11slide.ppt
11slide.ppt11slide.ppt
11slide.ppt
 
C#2
C#2C#2
C#2
 
Constructor
ConstructorConstructor
Constructor
 
Object-oriented Basics
Object-oriented BasicsObject-oriented Basics
Object-oriented Basics
 
Modern_Java_Workshop manjunath np hj slave
Modern_Java_Workshop manjunath np hj slaveModern_Java_Workshop manjunath np hj slave
Modern_Java_Workshop manjunath np hj slave
 
Constructors and Destructors
Constructors and DestructorsConstructors and Destructors
Constructors and Destructors
 
pyjamas22_ generic composite in python.pdf
pyjamas22_ generic composite in python.pdfpyjamas22_ generic composite in python.pdf
pyjamas22_ generic composite in python.pdf
 
Java ppt Gandhi Ravi (gandhiri@gmail.com)
Java ppt  Gandhi Ravi  (gandhiri@gmail.com)Java ppt  Gandhi Ravi  (gandhiri@gmail.com)
Java ppt Gandhi Ravi (gandhiri@gmail.com)
 
Static Analysis in IDEA
Static Analysis in IDEAStatic Analysis in IDEA
Static Analysis in IDEA
 
Java EE 6 CDI Integrates with Spring & JSF
Java EE 6 CDI Integrates with Spring & JSFJava EE 6 CDI Integrates with Spring & JSF
Java EE 6 CDI Integrates with Spring & JSF
 
Lego For Engineers - Dependency Injection for LIDNUG (2011-06-03)
Lego For Engineers - Dependency Injection for LIDNUG (2011-06-03)Lego For Engineers - Dependency Injection for LIDNUG (2011-06-03)
Lego For Engineers - Dependency Injection for LIDNUG (2011-06-03)
 
Learning C++ - Class 4
Learning C++ - Class 4Learning C++ - Class 4
Learning C++ - Class 4
 
Native Java with GraalVM
Native Java with GraalVMNative Java with GraalVM
Native Java with GraalVM
 
Haxe for Flash Platform developer
Haxe for Flash Platform developerHaxe for Flash Platform developer
Haxe for Flash Platform developer
 

More from People Strategists

MongoDB Session 3
MongoDB Session 3MongoDB Session 3
MongoDB Session 3
People Strategists
 
MongoDB Session 2
MongoDB Session 2MongoDB Session 2
MongoDB Session 2
People Strategists
 
MongoDB Session 1
MongoDB Session 1MongoDB Session 1
MongoDB Session 1
People Strategists
 
Android - Day 1
Android - Day 1Android - Day 1
Android - Day 1
People Strategists
 
Android - Day 2
Android - Day 2Android - Day 2
Android - Day 2
People Strategists
 
Overview of web services
Overview of web servicesOverview of web services
Overview of web services
People Strategists
 
Spring Framework - III
Spring Framework - IIISpring Framework - III
Spring Framework - III
People Strategists
 
Spring Framework-II
Spring Framework-IISpring Framework-II
Spring Framework-II
People Strategists
 
Spring Framework -I
Spring Framework -ISpring Framework -I
Spring Framework -I
People Strategists
 
Hibernate II
Hibernate IIHibernate II
Hibernate II
People Strategists
 
Hibernate III
Hibernate IIIHibernate III
Hibernate III
People Strategists
 
Hibernate I
Hibernate IHibernate I
Hibernate I
People Strategists
 
Identifing Listeners and Filters
Identifing Listeners and FiltersIdentifing Listeners and Filters
Identifing Listeners and Filters
People Strategists
 
Exploring Maven SVN GIT
Exploring Maven SVN GITExploring Maven SVN GIT
Exploring Maven SVN GIT
People Strategists
 
Agile Dev. II
Agile Dev. IIAgile Dev. II
Agile Dev. II
People Strategists
 
Agile Dev. I
Agile Dev. IAgile Dev. I
Agile Dev. I
People Strategists
 
Working with Servlets
Working with ServletsWorking with Servlets
Working with Servlets
People Strategists
 
Overview of JEE Technology
Overview of JEE TechnologyOverview of JEE Technology
Overview of JEE Technology
People Strategists
 
JSP Technology I
JSP Technology IJSP Technology I
JSP Technology I
People Strategists
 
XML Schemas
XML SchemasXML Schemas
XML Schemas
People Strategists
 

More from People Strategists (20)

MongoDB Session 3
MongoDB Session 3MongoDB Session 3
MongoDB Session 3
 
MongoDB Session 2
MongoDB Session 2MongoDB Session 2
MongoDB Session 2
 
MongoDB Session 1
MongoDB Session 1MongoDB Session 1
MongoDB Session 1
 
Android - Day 1
Android - Day 1Android - Day 1
Android - Day 1
 
Android - Day 2
Android - Day 2Android - Day 2
Android - Day 2
 
Overview of web services
Overview of web servicesOverview of web services
Overview of web services
 
Spring Framework - III
Spring Framework - IIISpring Framework - III
Spring Framework - III
 
Spring Framework-II
Spring Framework-IISpring Framework-II
Spring Framework-II
 
Spring Framework -I
Spring Framework -ISpring Framework -I
Spring Framework -I
 
Hibernate II
Hibernate IIHibernate II
Hibernate II
 
Hibernate III
Hibernate IIIHibernate III
Hibernate III
 
Hibernate I
Hibernate IHibernate I
Hibernate I
 
Identifing Listeners and Filters
Identifing Listeners and FiltersIdentifing Listeners and Filters
Identifing Listeners and Filters
 
Exploring Maven SVN GIT
Exploring Maven SVN GITExploring Maven SVN GIT
Exploring Maven SVN GIT
 
Agile Dev. II
Agile Dev. IIAgile Dev. II
Agile Dev. II
 
Agile Dev. I
Agile Dev. IAgile Dev. I
Agile Dev. I
 
Working with Servlets
Working with ServletsWorking with Servlets
Working with Servlets
 
Overview of JEE Technology
Overview of JEE TechnologyOverview of JEE Technology
Overview of JEE Technology
 
JSP Technology I
JSP Technology IJSP Technology I
JSP Technology I
 
XML Schemas
XML SchemasXML Schemas
XML Schemas
 

Recently uploaded

HCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAUHCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAU
panagenda
 
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUHCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
panagenda
 
Choosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptxChoosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptx
Brandon Minnick, MBA
 
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
saastr
 
dbms calicut university B. sc Cs 4th sem.pdf
dbms  calicut university B. sc Cs 4th sem.pdfdbms  calicut university B. sc Cs 4th sem.pdf
dbms calicut university B. sc Cs 4th sem.pdf
Shinana2
 
leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...
leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...
leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...
alexjohnson7307
 
Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
tolgahangng
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
Ivanti
 
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development ProvidersYour One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
akankshawande
 
Generating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and MilvusGenerating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and Milvus
Zilliz
 
Fueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte WebinarFueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte Webinar
Zilliz
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
innovationoecd
 
WeTestAthens: Postman's AI & Automation Techniques
WeTestAthens: Postman's AI & Automation TechniquesWeTestAthens: Postman's AI & Automation Techniques
WeTestAthens: Postman's AI & Automation Techniques
Postman
 
FREE A4 Cyber Security Awareness Posters-Social Engineering part 3
FREE A4 Cyber Security Awareness  Posters-Social Engineering part 3FREE A4 Cyber Security Awareness  Posters-Social Engineering part 3
FREE A4 Cyber Security Awareness Posters-Social Engineering part 3
Data Hops
 
Digital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
Digital Banking in the Cloud: How Citizens Bank Unlocked Their MainframeDigital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
Digital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
Precisely
 
Public CyberSecurity Awareness Presentation 2024.pptx
Public CyberSecurity Awareness Presentation 2024.pptxPublic CyberSecurity Awareness Presentation 2024.pptx
Public CyberSecurity Awareness Presentation 2024.pptx
marufrahmanstratejm
 
Introduction of Cybersecurity with OSS at Code Europe 2024
Introduction of Cybersecurity with OSS  at Code Europe 2024Introduction of Cybersecurity with OSS  at Code Europe 2024
Introduction of Cybersecurity with OSS at Code Europe 2024
Hiroshi SHIBATA
 
Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024
Jason Packer
 
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc
 
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing InstancesEnergy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
Alpen-Adria-Universität
 

Recently uploaded (20)

HCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAUHCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAU
 
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUHCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
 
Choosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptxChoosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptx
 
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
 
dbms calicut university B. sc Cs 4th sem.pdf
dbms  calicut university B. sc Cs 4th sem.pdfdbms  calicut university B. sc Cs 4th sem.pdf
dbms calicut university B. sc Cs 4th sem.pdf
 
leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...
leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...
leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...
 
Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
 
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development ProvidersYour One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
 
Generating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and MilvusGenerating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and Milvus
 
Fueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte WebinarFueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte Webinar
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
 
WeTestAthens: Postman's AI & Automation Techniques
WeTestAthens: Postman's AI & Automation TechniquesWeTestAthens: Postman's AI & Automation Techniques
WeTestAthens: Postman's AI & Automation Techniques
 
FREE A4 Cyber Security Awareness Posters-Social Engineering part 3
FREE A4 Cyber Security Awareness  Posters-Social Engineering part 3FREE A4 Cyber Security Awareness  Posters-Social Engineering part 3
FREE A4 Cyber Security Awareness Posters-Social Engineering part 3
 
Digital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
Digital Banking in the Cloud: How Citizens Bank Unlocked Their MainframeDigital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
Digital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
 
Public CyberSecurity Awareness Presentation 2024.pptx
Public CyberSecurity Awareness Presentation 2024.pptxPublic CyberSecurity Awareness Presentation 2024.pptx
Public CyberSecurity Awareness Presentation 2024.pptx
 
Introduction of Cybersecurity with OSS at Code Europe 2024
Introduction of Cybersecurity with OSS  at Code Europe 2024Introduction of Cybersecurity with OSS  at Code Europe 2024
Introduction of Cybersecurity with OSS at Code Europe 2024
 
Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024
 
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy Survey
 
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing InstancesEnergy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
 

Java Day-3

  • 1. © People Strategists - Duplication is strictly prohibited - www.peoplestrategists.com 1
  • 2. Day 3 Inheritance Advance Class Features 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 • 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
  • 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.) 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
  • 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.) 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
  • 9. 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
  • 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.) 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
  • 13. 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
  • 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.) public class Rectangle extends Shapes { Rectangle(){ noOfSides=4; } } © People Strategists - Duplication is strictly prohibited - www.peoplestrategists.com 16
  • 17. Inheritance Basic (Contd.) public class Pentagon extends Shapes { public Pentagon() { noOfSides=5; } } © People Strategists - Duplication is strictly prohibited - www.peoplestrategists.com 17
  • 18. Inheritance Basic (Contd.) public class Hexagon extends Shapes { public Hexagon() { noOfSides=6; } } © People Strategists - Duplication is strictly prohibited - www.peoplestrategists.com 18
  • 19. 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
  • 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.) 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
  • 23. 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
  • 24. 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
  • 25. 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
  • 26. 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
  • 27. 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
  • 28. 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
  • 29. 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
  • 30. 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
  • 31. 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
  • 32. 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
  • 33. 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
  • 34. 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
  • 35. 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
  • 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 Rectangle extends Shapes { Rectangle(){ noOfSides=4; } public void displayShapes(){ System.out.println("Rectangle"); } } © People Strategists - Duplication is strictly prohibited - www.peoplestrategists.com 37
  • 38. 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
  • 39. 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
  • 40. 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
  • 41. Advance Class Features © People Strategists - Duplication is strictly prohibited - www.peoplestrategists.com 41
  • 42. 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
  • 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.) 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
  • 45. 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
  • 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 • 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
  • 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.) 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
  • 52. 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
  • 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 • 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
  • 56. 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
  • 57. 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
  • 58. 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
  • 59. 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
  • 60. 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
  • 61. 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
  • 62. 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
  • 63. 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
  • 64. 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
  • 65. 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
  • 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 • 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
  • 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.) 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
  • 70. 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
  • 71. 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
  • 72. 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
  • 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 • 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
  • 75. 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
  • 76. 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
  • 77. 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
  • 78. 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
  • 79. 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
  • 80. Interface (Contd.) • The preceding code output will be: A4Paper Print A6Paper Print © People Strategists - Duplication is strictly prohibited - www.peoplestrategists.com 80
  • 81. 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
  • 82. 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
  • 83. 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
  • 84. 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