0% found this document useful (0 votes)
17 views61 pages

Java Module 3

Uploaded by

prathibhar070
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
17 views61 pages

Java Module 3

Uploaded by

prathibhar070
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 61

Inheritance..

• Inheritance is one of the three foundation principles


of object-oriented programming because it allows the
creation of hierarchical classifications.
• Using inheritance, you can create a general class that
defines traits common to a set of related items.
• This class can then be inherited by other, more
specific classes, each adding those things that are
unique to it.
Inheritance
•In the language of Java, a class that is inherited is
called a superclass.
• The class that does the inheriting is called a
subclass.
• Therefore, a subclass is a specialized version of a
superclass.
• It inherits all of the variables and methods defined by
the superclass and adds its own, unique elements.
Super Class

Sub Class
Inheritance Basics
•Java supports inheritance by allowing one class to incorporate
another class into its declaration.
• This is done by using the extends keyword.
• Thus, the subclass adds to (extends) the superclass
The general form of a class declaration that inherits a
superclass is shown here:
class subclass-name extends superclass-name {
// body of class }
class TwoDShape {

}
class Triangle extends TwoDShape
{

}
// A simple class hierarchy. class Shapes {
// A class for two-dimensional objects. public static void main(String args[]) {
class TwoDShape { Triangle t1 = new Triangle();

double width; Triangle t2 = new Triangle();
double height; t1.width = 4.0;
void showDim() { t1.height = 4.0;
System.out.println("Width and height t1.style = "isosceles";
are " + width + " and " + height); t2.width = 8.0;
} t2.height = 12.0;
} t2.style = "right";
//A subclass of TwoDShape for triangles. System.out.println("Info for t1: ");
class Triangle extends TwoDShape { t1.showStyle();
String style; t1.showDim();
double area() { System.out.println("Area is " +
return width * height / 2; t1.area());
} System.out.println();
void showStyle() { System.out.println("Info for t2: ");
System.out.println("Triangle is " + style); t2.showStyle();
} } t2.showDim();
System.out.println("Area is " +
t2.area()); } }
Inheritance Basics..
•In the example TwoDShape defines the attributes of a “generic” two-
dimensional shape, such as a square, rectangle, triangle, and so on.
•The Triangle class creates a specific type of TwoDShape, in this case, a
triangle.
• The Triangle class includes all of TwoDObject and adds the field style,
the method area( ), and the method showStyle( ).
• A description of the type of triangle is stored in style, area( ) computes and
returns the area of the triangle, and showStyle( ) displays the triangle style.
• Because Triangle includes all of the members of its superclass,
TwoDShape, it can access width and height inside area( ).
• Also, inside main( ), objects t1 and t2 can refer to width and height
directly, as if they were part of Triangle.
Inheritance Basics..
•Even though TwoDShape is a superclass for Triangle,
it is also a completely independent, stand-alone class.
• Being a superclass for a subclass does not mean
that the superclass cannot be used by itself.
• For example, the following is perfectly valid.
TwoDShape shape = new TwoDShape();
shape.width = 10;
shape.height = 20;
Shape.showDim();
Note: Java does not support the inheritance of
multiple superclasses into a single subclass.
Inheritance Basics..
•A major advantage of inheritance is that once you have created a
superclass that defines the attributes common to a set of objects, it
can be used to create any number of more specific subclasses.
• Each subclass can precisely tailor its own classification. For
example, here is another subclass of TwoDShape that encapsulates
Rectangles. class TwoDShape {
// A subclass of TwoDShape for rectangles. double width;
class Rectangle extends TwoDShape { double height;
boolean isSquare() { void showDim() {
if(width == height) return true; System.out.println("Width and
return false; height are " + width + " and " +
} height);}}
double area() { The Rectangle class includes TwoDShape
return width * height; and adds the methods isSquare( ), which
} determines if the rectangle is square, and
} area( ), which computes the area of a
rectangle.
Member Access and Inheritance
•As we already learned an instance variable of a class will be declared
private to prevent its unauthorized use or tampering.
•Inheriting a class does not overrule the private access restriction.
• Thus, even though a subclass includes all of the members of its
superclass, it cannot access those members of the superclass that have
been declared private.
•For example, if, as shown here, width and height are made private in
TwoDShape, then Triangle will not be able to access them.
// A subclass of TwoDShape for triangles.
// A class for two-dimensional class Triangle extends TwoDShape {
objects. String style;
class TwoDShape { double area() {
private double width; // these are return width * height / 2; // Error! can't
private double height; // now private access
....... }
} void showStyle() {
System.out.println("Triangle is " + style);} }
// A class for two-dimensional objects. class Shapes2 {
class TwoDShape { public static void main(String args[]) {
private double width; // these are Triangle t1 = new Triangle();

private double height; // now private Triangle t2 = new Triangle();
// Accessor methods for width and height. t1.setWidth(4.0);
double getWidth() { return width; } t1.setHeight(4.0);
double getHeight() { return height; } t1.style = "isosceles";
void setWidth(double w) { width = w; } t2.setWidth(8.0);
void setHeight(double h) { height = h; } t2.setHeight(12.0);
void showDim() { t2.style = "right";
System.out.println("Width and height are " + System.out.println("Info for t1: ");
width + " and " + height); t1.showStyle();
} t1.showDim();
} System.out.println("Area is " + t1.area());
System.out.println();
// A subclass of TwoDShape for triangles.
System.out.println("Info for t2: ");
class Triangle extends TwoDShape {
t2.showStyle();
String style;
t2.showDim();
double area() {
System.out.println("Area is " + t2.area());
return getWidth() * getHeight() / 2;
}
}
}
void showStyle() {
System.out.println("Triangle is " + style);
}
}
Constructors and Inheritance
• In a hierarchy, it is possible for both superclasses and
subclasses to have their own constructors.
• This raises an important question: what constructor is
responsible for building an object of the subclass, the one
in the superclass, the one in the subclass, or both?
• The answer is this: the constructor for the superclass
constructs the superclass portion of the object, and the
constructor for the subclass constructs the subclass part.
• This makes sense because the superclass has no
knowledge of or access to any element in a subclass.
•Thus, their construction must be separate.
Constructors and Inheritance...
•The preceding examples have relied upon the default
constructors created automatically by Java, so this was
not an issue.
•However, in practice, most classes will have explicit
constructors.
• When only the subclass defines a constructor, the
process is straightforward: simply construct the
subclass object.
• The superclass portion of the object is constructed
automatically using its default constructor.
// A class for two-dimensional objects. // A subclass of TwoDShape for triangles.
class TwoDShape { class Triangle extends TwoDShape {
private double width; // these are private String style;

private double height; // now private // Constructor
// Accessor methods for width and height. Triangle(String s, double w, double h) {
double getWidth() { return width; } setWidth(w);
double getHeight() { return height; } setHeight(h);
void setWidth(double w) { width = w; } style = s; }
void setHeight(double h) { height = h; } double area() {
void showDim() { return getWidth() * getHeight() / 2; }
System.out.println("Width and height are " + void showStyle() {
width + " and " + height); } } System.out.println("Triangle is " + style);}}
class Shapes3 {
public static void main(String args[]) {
Triangle t1 = new Triangle("isosceles", 4.0, 4.0);
Triangle t2 = new Triangle("right", 8.0, 12.0);
System.out.println("Info for t1: "); When only the subclass defines a constructor,
t1.showStyle(); the process is straightforward: simply
t1.showDim(); construct the subclass object. The superclass
System.out.println("Area is " + t1.area());
portion of the object is constructed
System.out.println();
System.out.println("Info for t2: "); automatically using its default constructor. For
t2.showStyle(); example, in the reworked version of Triangle
t2.showDim(); that defines a constructor. It also makes style
System.out.println("Area is " + t2.area()); }} private since it is now set by the constructor.
Using super to Call Superclass Constructors
• A subclass can call a constructor defined by its
superclass by use of the following form of super:
super(parameter-list);
•Here, parameter-list specifies any parameters needed
by the constructor in the superclass.
super( ) must always be the first statement
executed inside a subclass constructor.
•To see how super( ) is used, consider the version of
TwoDShape in the following program. It defines a
constructor that initializes width and height.
Note: Example Program is Shapes.java
// Add constructors to TwoDShape. // A subclass of TwoDShape for triangles.
class TwoDShape { class Triangle extends TwoDShape {
private double width; private String style;
private double height; Triangle(String s, double w, double h) {
// Parameterized constructor. super(w, h); // calls superclass constructor
TwoDShape(double w, double h) { style = s;}
width = w; double area() {
height = h; } return getWidth() * getHeight() / 2;}
void showStyle() {
// Accessor methods for width & height.
System.out.println("Triangle is " + style);}}
double getWidth() { return width; }
double getHeight() { return height; } class Shapes {
public static void main(String args[]) {
void showDim() {
Triangle t1 = new Triangle("isosceles", 4.0, 4.0);
System.out.println("Width and height Triangle t2 = new Triangle("right", 8.0, 12.0);
are " + System.out.println("Info for t1: ");
width + " and " + height); t1.showStyle();
} t1.showDim();
} System.out.println("Area is " + t1.area());
System.out.println();
System.out.println("Info for t2: ");
t2.showStyle();
t2.showDim();
System.out.println("Area is " + t2.area());}}
Considering Shapes.java
• Here, Triangle( ) calls super( ) with the parameters w
and h. This causes the TwoDShape( ) constructor to be
called, which initializes width and height using these
values.
•Triangle no longer initializes these values itself. It
need only initialize the value unique to it: style.
•This leaves TwoDShape free to construct its
subobject in any manner that it so chooses.
Furthermore,
•TwoDShape can add functionality about which
existing subclasses have no knowledge, thus
preventing existing code from breaking.
Parameterized Constructor in Super class
•Any form of constructor defined by the superclass
can be called by super( ). The constructor executed
will be the one that matches the arguments.
// Add more constructors to // Parameterized constructor.
//TwoDShape. TwoDShape(double w, double h) {
class TwoDShape { width = w;
private double width; height = h;
private double height; }
// A default constructor. // Parameterized Constructor for
TwoDShape() { //object with equal width and height.
width = height = 0.0; TwoDShape(double x) {
} width = height = x;
}
Invoking the constructor discussed in the previous slide...
// A subclass of TwoDShape for triangles.
class Triangle extends TwoDShape {
private String style;
// A default constructor.
Triangle() {
super();
style = "null";
}
// Constructor
Triangle(String s, double w, double h) {
super(w, h); // call superclass constructor
style = s;
}
// Construct an isosceles triangle.
Triangle(double x) {
super(x); // call superclass constructor
style = "isosceles";
} ......................
Creating a Multilevel Hierarchy
• We can build hierarchies that contain as many layers
of inheritance as you like.
• As mentioned, it is perfectly acceptable to use a
subclass as a superclass of another.
• For example, given three classes called A, B, and C
• C can be a subclass of B, which is a subclass of A.
• When this type of situation occurs, each subclass
inherits all of the traits found in all of its
superclasses.
• In this case, C inherits all aspects of B and A.
Creating a Multilevel Hierarchy..
• Consider the following program:
• In it, the subclass Triangle is used as a superclass to create the subclass called
ColorTriangle.
• ColorTriangle inherits all of the traits of Triangle and TwoDShape and adds a
field called color, which holds the color of the triangle.

// A multilevel hierarchy. // Construct object with equal width


class TwoDShape { and //height.
private double width; TwoDShape(double x) {
private double height; width = height = x; }
// A default constructor. // Accessor methods for width and
TwoDShape() { height.
width = height = 0.0; double getWidth() { return width; }
} double getHeight() { return height; }
// Parameterized constructor. void showDim() {
TwoDShape(double w, double h) { System.out.println("Width and height are
width = w; " + width + " and " + height);
height = h; }
} }
Creating a Multilevel Hierarchy...
// Extend TwoDShape. // Extend Triangle.
class ColorTriangle extends Triangle {
class Triangle extends TwoDShape {
private String color;
private String style; ColorTriangle(String c, String s,
// A default constructor. double w, double h) {
Triangle() { super(s, w, h);
super(); color = c; }
String getColor() { return color; }
style = "null“;} void showColor() {
Triangle(String s, double w, double h) { System.out.println("Color is " + color); }}
super(w, h); // call superclass constructor class ShapesMain {
style = s;} public static void main(String args[]) {
ColorTriangle t1 =
// Construct an isosceles triangle. new ColorTriangle("Blue", "right", 8.0, 12.0);
Triangle(double x) { ColorTriangle t2 =
super(x); // call superclass constructor new ColorTriangle("Red", "isosceles", 2.0, 2.0);
style = "isosceles“;} System.out.println("Info for t1: ");
t1.showStyle(); t1.showDim(); t1.showColor();
double area() {
System.out.println("Area is " + t1.area());
return getWidth() * getHeight() / 2;} System.out.println();
void showStyle() { System.out.println("Info for t2: ");
System.out.println("Triangle is " + t2.showStyle();
t2.showDim();
style);} }
t2.showColor();
System.out.println("Area is " + t2.area()); } }
Creating a Multilevel Hierarchy..
Because of inheritance, ColorTriangle can make
use of the previously defined classes of
Triangle and TwoDShape, adding only the extra
information it needs for its own, specific
application. This is part of the value of
inheritance; it allows the reuse of code.
This example illustrates one other important
point: super( ) always refers to the constructor
in the closest superclass. The super( ) in
ColorTriangle calls the constructor in Triangle.
The super( ) in Triangle calls the constructor in
TwoDShape. In a class hierarchy, if a superclass
constructor requires parameters, then all
subclasses must pass those parameters “up the
line.”
This is true whether or not a subclass needs
parameters of its own.
When Are Constructors Called?
• In the foregoing discussion of inheritance and class hierarchies,
an important question may have occurred to you: When a
subclass object is created, whose constructor is executed first, the
one in the subclass or the one defined by the superclass?
• For example, given a subclass called B and a superclass called
A, is A’s constructor called before B’s, or vice versa?
• The answer is that in a class hierarchy, constructors are called in
order of derivation, from superclass to subclass.
• Further, since super( ) must be the first statement executed in
a subclass’ constructor, this order is the same whether or not
super( ) is used.
• If super( ) is not used, then the default (parameterless)
constructor of each superclass will be executed.
• The following program illustrates when constructors are
executed:
Creating a Multilevel Hierarchy
// Create a super class.
class A {
A() { The output from this program is shown here:
System.out.println("Constructing A."); Constructing A.
}} Constructing B.
// Create a subclass by extending class A. Constructing C.
class B extends A {
B() {
System.out.println("Constructing B.");
}
}
// Create another subclass by extending B.
class C extends B {
C() {
System.out.println("Constructing C.");
}
}
class OrderOfConstruction {
public static void main(String args[]) {
C c = new C();
}
}
Superclass References and Subclass Objects
• Java is a strongly typed language. Aside from the standard conversions
and automatic promotions that apply to its primitive types, type
compatibility is strictly enforced.
• Therefore, a reference variable for one class type cannot normally refer
to an object of another class type.
For example, consider the following program: Here, even though
class X and class Y
// This will not class IncompatibleRef { are physically the
compile. public static void main(String same, it is not
args[]) { possible to assign
class X { an X reference to a
int a; X x = new X(10); Y object because
X(int i) { a = i; } } X x2; they have different
Y y = new Y(5); types. In general,
class Y { an object reference
int a; x2 = x; // OK, both of same type variable can refer
Y(int i) { a = i; } } x2 = y; // Error, not of same type only to objects of
}} its type.
Superclass References and Subclass Objects..
• There is, however, an important exception to Java’s strict type enforcement.
• A reference variable of a superclass can be assigned a reference to any subclass
derived from that superclass.
Here is an example: class SupSubRef {
public static void main(String args[]) {
// A superclass reference can X x = new X(10);
refer to a subclass //object. X x2;
class X { Y y = new Y(5, 6);
int a; x2 = x; // OK, both of same type
System.out.println("x2.a: " + x2.a);
X(int i) { a = i; }
x2 = y; // still Ok because Y is derived from X
} System.out.println("x2.a: " + x2.a);
class Y extends X { // X references know only about X members
int b; x2.a = 19; // OK
Y(int i, int j) { // x2.b = 27; // Error, X doesn't have a b
super(j); member } }
b = i;
}}
Explanation for program given in the previous slide
• Here, Y is now derived from X; thus it is permissible for
x2 to be assigned a reference to a Y object.
• It is important to understand that it is the type of the reference
variable— not the type of the object that it refers to—that
determines what members can be accessed.
• That is, when a reference to a subclass object is assigned to a
superclass reference variable, you will have access only to
those parts of the object defined by the superclass.
• This is why x2 can’t access b even when it refers to a Y
object.
• If you think about it, this makes sense, because the
superclass has no knowledge of what a subclass adds to it.
• This is why the last line of code in the program is commented
out.
Method Overriding
• In a class hierarchy, when a method in a subclass has
the same return type and signature as a method in its
superclass, then the method in the subclass is said to
override the method in the superclass.
• When an overridden method is called from within a
subclass, it will always refer to the version of that
method defined by the subclass.
• The version of the method defined by the superclass
will be hidden.
Method Overriding..
// Method overriding. // display k – this overrides show() in A
class A { void show() {
int i, j; System.out.println("k: " + k);
A(int a, int b) { }
i = a; }
class Override {
j = b;
public static void main(String args[]) {
} B subOb = new B(1, 2, 3);
// display i and j subOb.show(); // this calls show() in B
void show() { }
System.out.println("i and j: " + i + " " +}
j);
}
} The output produced by this program is shown here:
class B extends A { k: 3
int k;
B(int a, int b, int c) {
super(a, b); When show( ) is invoked on an object of type B, the version of
k = c; show( ) defined within B is used. That is, the version of show( )
} inside B overrides the version declared in A.
Explanation for program given in the previous slide
If you want to access the superclass version of an overridden method, you can do
so by using super. For example, in this version of B, the superclass version of
show( ) is invoked within the subclass’ version. This allows all instance variables to
be displayed.
// Method overriding. class B extends A {
class A { int k;
int i, j; B(int a, int b, int c) {
A(int a, int b) { super(a, b);
i = a; k = c;
j = b; }
} void show() {
// display i and j super.show(); // this calls A's show()
void show() { System.out.println("k: " + k); } }
System.out.println("i and j: " + i + " " +
j); } }
Here, super.show( ) calls the superclass version of show( ).
If you substitute this version of show( ) Method overriding occurs only when the return
into the previous program, you will see types and signatures of the two methods
the following output: are identical. If they are not, then the two
i and j: 1 2 methods are simply overloaded. (It is already
k: 3 discussed)
Overridden Methods Support Polymorphism
• Method overriding forms the basis for one of Java’s most
powerful concepts: dynamic method dispatch.
• Dynamic method dispatch is the mechanism by which a
call to an overridden method is resolved at run time
rather than compile time.
• Dynamic method dispatch is important because this is
how Java implements run-time polymorphism.
• When an overridden method is called through a
superclass reference, Java determines which version of
that method to execute based upon the type of the object
being referred to at the time the call occurs. Thus, this
determination is made at run time.
Overridden Methods Support Polymorphism..
• When different types of objects are referred to, different
versions of an overridden method will be called.
• In other words, it is the type of the object being referred
to (not the type of the reference variable) that determines
which version of an overridden method will be executed.
• Therefore, if a superclass contains a method that is
overridden by a subclass, then when different types of
objects are referred to through a superclass reference
variable, different versions of the method are executed.
Overridden Methods Support Polymorphism..
// Demonstrate dynamic method class DynDispDemo {
dispatch. public static void main(String args[]) {
class Sup { Sup superOb = new Sup();
void who() { Sub1 subOb1 = new Sub1();
System.out.println("who() in Sup");}} Sub2 subOb2 = new Sub2();
class Sub1 extends Sup { Sup supRef;
void who() { supRef = superOb;
System.out.println("who() in Sub1");}} supRef.who();
class Sub2 extends Sup { supRef = subOb1;
void who() { supRef.who();
System.out.println("who() in Sub2"); }} supRef = subOb2;
supRef.who(); } }
The output from
the program is This program creates a superclass called Sup and two subclasses of it,
shown here: called Sub1 and Sub2. Sup declares a method called who( ), and the
who() in Sup subclasses override it. Inside the main( ) method, objects of type Sup,
who() in Sub1 Sub1, and Sub2 are declared. Also, a reference of type Sup, called
supRef, is declared. The program then assigns a reference to each type of
who() in Sub2
object to supRef and uses that reference to call who( ). As the output
shows, the version of who( )executed is determined by the type of object
being referred to at the time of the call, not by the class type of supRef.
Why Overridden Methods?
• Overridden methods allow Java to support run-time polymorphism.
• Polymorphism is essential to object-oriented programming for one reason: it
allows a general class to specify methods that will be common to all of its
derivatives, while allowing subclasses to define the specific implementation of
some or all of those methods.
• Overridden methods are another way that Java implements the “one interface,
multiple methods” aspect of polymorphism.
• Part of the key to successfully applying polymorphism is understanding that
the superclasses and subclasses form a hierarchy that moves from lesser to
greater specialization.
• Used correctly, the superclass provides all elements that a subclass can use
directly.
• It also defines those methods that the derived class must implement on its own.
• This allows the subclass the flexibility to define its own methods, yet still
enforces a consistent interface.
• Thus, by combining inheritance with overridden methods, a superclass can
define the general form of the methods that will be used by all of its subclasses.
Abstract Classes
• A class which is declared with the abstract keyword is known as
an abstract class in Java.
• It can have abstract and non-abstract methods (method with the
body). abstract class Bike{
abstract void run();
}
class Honda4 extends Bike{
void run()
{
System.out.println("running safely");
}
public static void main(String args[]){
Bike obj = new Honda4();
obj.run(); }
}
Using Abstract Classes
• Sometimes you will want to create a superclass that
defines only a generalized form that will be shared by all
of its subclasses, leaving it to each subclass to fill in the
details.
• Such a class of the methods that the subclasses must
implement but does not, itself, provide an
implementation of one or more of these methods.
• One way this situation can occur is when a superclass is
unable to create a meaningful implementation for a
method.
• As you create your own class libraries, it is not
uncommon for a method to have no meaningful
definition in the context of its superclass.
Using Abstract Classes
• An abstract method is created by specifying the abstract
type modifier. An abstract method contains no body
and is, therefore, not implemented by the superclass.
• Thus, a subclass must override it—it cannot simply use
the version defined in the superclass.
• To declare an abstract method, use this general form:
abstract return-type name(parameter-list);
• As you can see, no method body is present.
• The abstract modifier can be used only on normal
methods. It cannot be applied to static methods or to
constructors.
Using Abstract Classes
abstract class Shape{
abstract void draw(); }
//
In real scenario, implementation is provided by others i.e. unknown by /
/end user
class Rectangle extends Shape{
void draw(){ System.out.println("drawing rectangle");}
}
class Circle1 extends Shape{
void draw(){System.out.println("drawing circle");}
}
//In real scenario, method is called by programmer or user
class TestAbstraction1{
public static void main(String args[]){
Circle1 c=new Circle1();
Rectangle r =new Rectangle();
c.draw();
Using final
• As powerful and useful as method overriding and inheritance are,
sometimes you will want to prevent them.
• For example, you might have a class that encapsulates control of
some hardware device.
• Further, this class might offer the user the ability to initialize the
device, making use of private, proprietary information.
• In this case, you don’t want users of your class to be able to override
the initialization method.
• Whatever the reason, in Java it is easy to prevent a method from
being overridden or a class from being inherited by using the
keyword final.
final Prevents Overriding
• To prevent a method from being overridden, specify final as a
modifier at the start of its declaration. Methods declared as final
cannot be overridden.
Using of final..
class A {
•Because meth( )
final void meth() {
System.out.println("This is a final is declared as
method."); final, it cannot be
} overridden in B.
•If you attempt to
}
class B extends A { do so, a compile-
void meth() { // ERROR! Can't override. time error will
System.out.println("Illegal!"); result.
}
}
Using of final Prevents Inheritance
• You can prevent a class from being inherited by preceding its
declaration with final.
• Declaring a class as final implicitly declares all of its methods as
final, too.
• As you might expect, it is illegal to declare a class as both abstract
and final since an abstract class is incomplete by itself and relies
upon its subclasses to provide complete implementations.
final class A {
// ...
}
// The following class
is //illegal.
class B extends A { //
ERROR! Can't subclass A
// ...
}
Using final with Data Members
• In addition to the uses of final just shown, final can also be applied
to variables to create what amounts to named constants.
• If you precede a class variable’s name with final, its value cannot be
changed throughout the lifetime of your program.
• You can, of course, give that variable an initial value.
Interfaces
• A named collection of method declarations.
• A Java interface is a collection of constants and abstract
methods
• Since all methods in an interface are abstract, the abstract
modifier is usually left off
• Using interface, you can specify what a class must do, but
not how it does.
• Interface fields are public, static and final by default, and
methods are public and abstract.
Advantages of interfaces:
• It is used to achieve abstraction.
• By interface, we can support the functionality of multiple
inheritances.
Implementing Interfaces
• Once an interface has been defined, one or more classes can implement
that interface.
• To implement an interface, include the implements clause in a class
definition, and then create the methods defined by the interface.
• The general form of a class that includes the implements clause looks
like this:
class classname [extends superclass] [implements interface1
[,interface2...]] {
// class-body
}
• If a class implements more than one interface, the interfaces are
separated with a comma.
• The methods that implement an interface must be public. Also, the type
signature of implementing method must match exactly the type
signature specified in interface definition.
Java Program to implement Interface
interface Moveable
{
int AVG_SPEED=30;
void Move();
}
class Move implements Moveable
{
void Move(){
System .out. println ("Average speed is: "+AVG_SPEED ); }
}
class Vehicle
{
public static void main (String[] arg)
{
Move m = new Move();
m.Move(); }
Java Program to implement Interface..
interface Teacher
{ void display1(); }
interface Student
{ void display2(); }
class College implements Teacher, Student {
public void display1() { System.out.println("Hi I am Teacher"); }
public void display2() { System.out.println("Hi I am Student"); } }
class CollegeData {
public static void main(String args[]) {
College c=new College();
c.display1();
c.display2();
}
}
Interfaces can be extended
• One interface can inherit another by use of the keyword
extends.
• The syntax is the same as for inheriting classes.
• When a class implements an interface that inherits
another interface, it must provide implementations for all
methods defined within the interface inheritance chain.
• Example: Java program to demonstrate interfaces can be
extended with extend keyword.
Interfaces can be extended..

interface Teacher {
{ void display1(); }
interface Student { class Class_Interface
void display2(); } {
interface T_S extends Teacher, public static void
Student {
void display3(); }
main(String args[])
class College implements T_S { {
public void display1() { College c=new College();
System.out.println("Hi I am c.display1();
Teacher"); }
public void display2() {
c.display2();
System.out.println("Hi I am c.display3();
Student"); } }
public void display3() { }
System.out.println("Hi I am
Teacher_Student"); } }
Java program to implement interface and inheriting the properties from a class

class Interface_Class
interface Teacher {
{ public static void main(String
void display1();
arh[])
}
class Student {
{ College c=new College();
void display2() c.display1();
{ c.display2();
System.out.println("Hi I am Student"); }
} } }
class College extends Student
implements Teacher
{
public void display1()
{
System.out.println("Hi I am
Teacher"); } }
Interfaces Can Be Extended
• One interface can inherit another by use of the keyword extends.
• When a class implements an interface that inherits another interface,
• it must provide implementations for all methods defined within the interface
inheritance chain.
Following is an example:
interface A { class IFExtend {
void meth1(); public static void main(String
void meth2(); }
// B now includes meth1() and meth2() --
args[]) {
it //adds meth3(). MyClass ob = new MyClass();
interface B extends A { ob.meth1();
void meth3(); } ob.meth2();
// This class must implement all of A and B
class MyClass implements B {
ob.meth3();
public void meth1() { }
System.out.println("Implement meth1()."); } }
public void meth2() {
System.out.println("Implement meth2()."); }
public void meth3()
{System.out.println("Implement
meth3().");} }
Java Default Methods
•Java provides a facility to create default methods inside the interface.
•Methods which are defined inside the interface and tagged with default
are known as default methods. So these methods can be given the
implementation inside the interface itself.
•These methods are non-abstract methods.
Example:
•In the following example, TestDefault is a functional interface that
contains a default and an abstract method.
•The concept of default method is used to define a method with default
implementation.
• You can override default method also to provide more specific
implementation for the method.
interface TestDefault{
// Default method
default void disp(){
System.out.println("Hello, I am in default method");
}
// Abstract method
void dispAb(String msg);
}
public class DefaultMethod implements TestDefault{
public void dispAb(String msg){ // implementing abstract method
System.out.println(msg);
}
public static void main(String args[]) {
DefaultMethod dfm = new DefaultMethod();
dfm.disp(); // calling default method
dfm.dispAb(“I am in Abstract method"); // calling abstract method
}
}
Static Methods in Interface
•Static Methods in Interface are those methods, which are defined in
the interface with the keyword static.
•Unlike other methods in Interface, these static methods contain the
complete definition of the function and since the definition is complete
and the method is static, therefore these methods cannot be overridden
or changed in the implementation class.
•To use a static method, Interface name should be instantiated with it,
as it is a part of the Interface only.
interface TestInterface {
// static method
static void testStatic ()
{
System.out.println(“I am in Static Method”);
}
// Public and abstract method of Interface
void testAb(String str); }

// Implementation Class
public class InterfaceDemo implements TestInterface {
public static void main(String args[])
{
InterfaceDemo interfaceDemo = new InterfaceDemo();

// Calling the static method of interface with the help of interface


TestInterface.testStatic();

// Calling the abstract method of interface


interfaceDemo.testAb(“Abstract method Overridden”);
}

// Implementing interface method


@Override
public void testAb(String str)
{
System.out.println(str);
Local Variable type inference
•Local variable type inference is a feature in Java 10 that allows the developer to
skip the type declaration associated with local variables (those defined inside
method definitions, initialization blocks, for-loops, and other blocks like if-else),
and the type is inferred by the JDK.
•It allows to define a variable using var and without specifying the type of it. The
compiler infers the data type of the variable using the value provided. This type
inference is restricted to local variables.
class A {
public static void main(String
args[])
// Declaring iteration variables in enhanced for loops
{
class A {
var x = "Hi there";
public static void main(String args[])
System.out.println(x)
{
}
int[] arr = new int[3];
}
arr = { 1, 2, 3 };
for (var x : arr)
System.out.println(x + "\n");
Output: Hi there
} }
Output:
1
2
3
Private Interface Methods
•In Java 9, we can create private methods inside an interface. Interface allows us
to declare private methods that help to share common code between non-
abstract methods.
interface Sayable{
default void say() {
saySomething();
}
// Private method inside interface
private void saySomething() {
System.out.println("Hello... I'm private method");
}
}
public class PrivateInterface implements Sayable {
public static void main(String args[]) {
Sayable s = new PrivateInterface();
s.say();
}
}
The Object Class
• Java defines one special class called Object that is an implicit
superclass of all other classes. In other words, all other classes are
subclasses of Object.
• This means that a reference variable of type Object can refer to an
object of any other class.
• Also, since arrays are implemented as classes, a variable of type Object
can also refer to any array.
• The Object class defines the basic state and behavior that all objects
must have, such as the ability to compare oneself to another object, to
convert to a string, to wait on a condition variable, to notify other
objects that a condition variable has changed, and to return the object's
class.
The Object Class..
Object defines the following methods, which means that they are available in every
object.
The Object Class..

You might also like