Академический Документы
Профессиональный Документы
Культура Документы
Inheritance allows classes to inherit commonly used instance variables and methods from other
classes.An inherited class will have all the features of its parent classes and can also have its own
instance variables and methods.
In single inheritance, a class is derived from one direct superclass. In multiple inheritance, a class
is derived from more than one direct superclass. Java does not support multiple inheritance.
A subclass is more specific than its superclass and represents a smaller group of objects.
Every object of a subclass is also an object of that class’s superclass. However, a superclass
object is not an object of its class’s subclasses.( Assigning base Class refrence to SuperClass)
The inheritance IS-A relationship works in only one direction! Triangle IS-A Shape makes sense,
so you can have Triangle extend Shape. But the reverse—Shape IS-A Triangle—does not make
sense, so Shape should not extend Triangle. Remember that the IS-A relationship implies that if
X IS-A Y, then X can do anything a Y can do (and possibly more)..Inheritance is not mutual.
If class B extends class A, class B IS-A class A. This is true anywhere in the inheritance tree. If
class C extends class B, class C passes the IS-A test for both B and A.
Cuboid
public int height;
1
A Simple inheritance program
We say that the subclass extends the superclass. An inheritance relationship means that the
subclass inherits the members(the instance variables and methods.) of the superclass.
subclass can add new methods and instance variables of its own, and it can override the
methods it inherits from the superclass
When a class is inherited, the child class can access all features of the parent class as if it were
declared in its class.
Advantage: Once the class is developed and tested ,its code can be used by the other classes.Inheritance
avoid rewriting the code.
Rectangle.java //SuperClass
public class Rectangle {
int length;
int breadth;
Cuboid.java //SubClass
int height;
2
RectCubTest.java
}
}
OUTPUT
As you can see, the subclass Cuboid includes all of the members of its superclass, Rectangle.
This is why Cuboid RefrenceVariable “c” can access lenght and breadth and call
showLengthBreadth( ) method of its superClass(i. Rectangle.) Also, inside volume( ), length and
breadth are accessed directly as if they were the part of Cuboid.
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
3
METHOD OVERIDING
Whatever the superclass takes as an argument, the subclass overriding the method must
use that same argument. And whatever the superclass declares as a return type, the
overriding method must declare either the same type, or a subclass type.
super Keyword
The super keyword is really a reference to the superclass portion of an object. When
subclass code uses super, as in super.runReport(), the superclass version of the method
will run.
The keyword super lets you invoke a superclass version of an overridden method, from within
the subclass.super.area();
4
public class Parallelogram
{
5
Triangle.java
public class Triangle extends Parallelogram
{
public Triangle( )
{
super();// calling parallelogram constructor
}
ParallelogramTriangleTest.java
OUTPUT
Area of Paralleogram = 20.0
Area of Triangle is = 21.0
6
When the compiler encounters a method call made through a variable, the compiler
determines if the method can be called by checking the variable’s class type. If that class
contains the proper method declaration (or inherits one), the call is compiled. At
execution time, the type of the object to which the variable refers determines the actual
method to use.
Most method calls are resolved at execution time, based on the type of the object being
manipulated.
This process is known as dynamic binding or late binding.
A superclass reference can be used to invoke only methods of the superclass (and the
superclass can invoke overridden versions of these in the subclass).
super KeyWord
The super keyword is really a reference to the superclass portion of an object. When
subclass code uses super, as in super.volume(), the superclass version of the method will
run.
The keyword super lets you invoke a superclass version of an overridden method, from
within the subclass .super.area();
The compiler decides whether you can call a method based on the reference type, not the actual
object type.
Shape
Cylinder
Cone
7
Shape.java
public Shape()
{
//Calling overloaded two argument constructor Shape(int r, int h )
this( 0, 0 );
}
public Shape( int r, int h )
{
radius = r;
height = h;
}
public float volume()
{
return 0.0f;
}
}
Sphere.java
public class Sphere extends Shape {
public Sphere()
{
super(); //calling Shape constructor
}
public Sphere(int r, int h )
{
super( r, h ); //calling Shape( int r, int h) constructor
}
public float volume()
{
return 3.14f * radius * radius * height;
}
}
Cone.java
public class Cone extends Sphere
{
public Cone(int r, int h)
{
super( r, h ); //calling Sphere( int r, int h) constructor
}
8
ShapeSphereConeTest.java
OUTPUT
Shape volume is = 0.0
Volume of Sphere is = 251.20001
Volume of Cone is = 263.76
shpRef = sph;
In java it is possible to assign a subclass reference to superclass.We are
assigning the subclass reference “sph” to the superClass reference variable
“shpRef”.
At the runtime JVM will call the method based on the type of object it is
referring to
shpRef.volume();
will call the overridden method declared in the Sphere class not the Shape
class
9
ABSTRACT CLASSES AND ABSTRACT METHDOS( polymorphism)
Polymorphism: Abstract Classes and Abstract Methods promotes 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.
Some classes just should not be instantiated!If we don’t want the class to be instantiated mark
the class abstract.
There’s a simple way to prevent a class from ever being instantiated. In other words, to stop
anyone from saying “new” on that type. By marking the class as abstract, the compiler will stop
any code, anywhere, from ever creating an instance of that type.
You can still use that abstract type as a reference type(to use it as a polymorphic argument or
return type, or to make a polymorphic array).
Concrete classes are those that are specifi c enough to be instantiated. A concrete class just
means that it’s OK to make objects of that type.
An abstract class defines a common interface for the various members of a class hierarchy.
The abstract class contains methods that will be defined in the subclasses. All classes in the
hierarchy can use this same interface through polymorphism.
10
Abstract methods
An abstract class means the class must be extended; an abstract method means the method must be
overridden No method body !End it with a semicolon.
public abstract float area ();
If you declare an abstract method, you MUST mark the class abstract as well. You can’t have
an abstract method in a non-abstract class.
Abstract methods don’t have a body; they exist solely for polymorphism. That means the first
concrete class in the inheritance tree must implement all abstract methods.
implement the abstract method”, that means you must provide a bodyThat means you must
create a non-abstract method in your class with the same method signature (name and
arguments) and a return type that is compatible with the declared return type of the abstract
method.
abstract Shape3D
int radius;
int height;
RtCircularCylinder RtCircularCone
int slantHeight;
11
//Shape3D.java
public abstract class Shape3D {
public int radius;
public int height;
}
public double CSA()
{
return Math.PI * radius * slantHeight;
}
}
12
//Shape3DTest.java
OUTPUT
Shape3D shp;
At the runtime JVM will call the method based on the type of object it is
referring to.
similarly for
13
USING FINAL TO PREVENT INHERITANCE
A class declared final cannot be extended, and every method in it is implicitly final.
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.
abstract Employee
String name;
String empId
the method
14
Boss.java
HourlyWorker.java
EmployeeTest.java
public class EmployeeTest {
public static void main(String args[])
{
//can create only refvar “e” for abstract class(NO OBJECT CREATION)
Employee e;
Boss b = new Boss("Bushra", "E18");
b.monthlySalary = 50000;
15
HourlyWorker hw = new HourlyWorker("Amina","E02", 200, 6);
System.out.println("\nDetails of HourlyWorker");
System.out.println("name = " + e.name );
System.out.println("HourlyWorker eID = " + e.empId);
System.out.println("HourlyWorker wageRate = " + hw.wages);
System.out.println("HourlyWorker hoursWorked = " + hw.hours);
System.out.println("HourlyWorker sal is = " + e.salary());
}
}
OUTPUT
Details of Boss
name = Bushra
Boss eIS = E18
Boss sal is = 50000.0
Details of HourlyWorker
name = Amina
HourlyWorker eID = E02
HourlyWorker wageRate = 200
HourlyWorker hoursWorked = 6
HourlyWorker sal is = 1200.0
Employee e;
Boss b = new Boss("Bushra", "E18");
e = b; // Assigning sublclass ref to superclass ref
e.salary()
e.salary()
will call the overridden method declared in the Boss class not the Employee
class
16
FINAL VARIABLES AND METHODS
variables can be declared final to indicate that they cannot be modified after they are declared and that
they must be initialized when they are declared.
It is also possible to define methods and classes with the final modifier.
Methods that are declared static and methods that are declared private are implicitly final.
Because a final method’s definition can never change, the compiler can optimize the program by
removing calls to final methods and replacing them with the expanded code of their definitions
at each method call location—a technique known as inlining the code.
17
Feature Interface Abstract class
18
Multiple Inheritance problem in java: Java does not promote multiple inheritance.i.e
extending from two class. But it isn’t, because multiple inheritance has a problem known as The
Deadly Diamond of Death.
CDBurner and
DVDBurner both
inherit from
DigitalRecorder,
Imagine that the “i” instance
and both override the variable is used by both
burn() CDBurner and DVDBurner, with
different values.
A Java interface solves your multiple inheritance problem by giving you much of the
polymorphic benefi ts of multiple inheritance without the pain and suffering from the
Deadly Diamond of Death (DDD).
Interfaces are the ultimate in flexibility, because if you use interfaces instead of concrete
subclasses (or even abstract superclass types) as arguments and return types, you can pass
anything that implements that interface.
A class can extend one class, and implement an interface Use an interface when you want to
defi ne a role that other classes can play, regardless of where those classes are in the
inheritance tree.
19
A Java interface is like a 100% pure abstract class.
<<interface>>
Shape
All methods in an interface are abstract, so any class that IS-A Shape MUST implement
(i.e. override) the methods of Shape.
An interface is defined much like a class. This is the general form of an interface:
Create an interface using the interface keyword instead of the word class
20
IMPLEMETING INTERFACES
Implement an interface using the keyword implements
To IMPLEMENT an interface:
In fact, objects of any class that extends Circle are also Shape objects.
When you call a method through one of these references, the correct version
will be called based on the actual instance of the interface being referred
to.
21
Shape.java
public interface Shape {
<<interface>>
public abstract float area(); Shape
public abstract float volume();
}
_______________________________________________
public abstract float area();
Circle.java public abstract float volume();
public class Circle implements Shape {
int radius;
public Circle(int r) {
radius = r; Circle
}
22
//Convert instance variables of to a String representation
public String toString()
{
return super.toString() +
"\n height = " + height;
}
}
_______________________________________________________________________
ShapeTest.java
public class ShapeTest {
public static void main(String args[])
{
Shape shp;
OUTPUT
Implicitly calling the toString() of Circle
radius = 4
23
Area of Cylinder is = 345.40002
Volume of Cylinder is = 471.0
VARIABLES IN INTERFACES
Variables in an interface are implicitly marked as final and static.
Another use of interfaces is to define a set of constants that can be used in many class
definitions. Consider interface Constants
public interface Constants {
public static final int ONE = 1;
public static final int TWO = 2;
}
Classes that implement interface Constants can use ONE, TWO and THREE anywhere in the
class definition. A class can even use these constants by importing the interface, then referring to
each constant as Constants.ONE, Constants.TWO and Constants. THREE
<<interface>>
Constants
Addition
24
Addition.java
ConstantsAdditionTest.java
OUTPUT
Sum of constans is 6
Constants con ;
We are creating con reference variable referring to the Constants interface.
25
EXTENDING INTERFACES
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.
<<interface>>
A
<<interface>>
B
InterfaceExtension
A.java
public interface A
{
public abstract void methodA();
public abstract void methodB();
B.java
26
InterfaceExtension.java
IFExtTest.java
OUTPUT
Method A is overridden
method B is overridden
Method C is overridden
27
IMPLEMENTING MULTIPLE INTERFACE:
When a class implements multiple interface it has to override all the abstract methods declared in
the interface it is implmenting.
<<interface>>
Constants
<<interface>> <<interface>>
Multiplication Subtraction
Constants.java
28
Multiplication.java
Subtraction.java
Arithmetic1.java
29
ArithmeticTest.java
diff = arth.subtract();
System.out.println("Difference = " + diff);
OUTPUT
Product = 20
Difference = 2
30
IMPLEMENTING MULTIPLE INTERFACE EXTRA
When a class implements multiple interface it has to override the abstract methods declared in
the interface.
The class must override all the abstract method of the different interfaces it is implementing.
<<interface>>
Multiplication
<<interface>>
Statistics
public static final float PI = 3.14f
Calculator
31
public interface Statistics {
32
public class CalculatorTest {
public static void main(String args[])
{
Arithmetic arth;
Calculator calc = new Calculator();
int sum = calc.addition( 2, 4 );
System.out.println("Addition Result = " + sum);
Statistics stat;
OUTPUT
Addition Result = 6
Subtraction Result = -1
Multiplication Result = 56
Division Result = 0.9
Mean Value = 15.0
Mean Value = 35.0
33