Java Module 3
Java Module 3
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.
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();