OOPS With Java-Module 3
OOPS With Java-Module 3
Module -3
Chapter -1 Inheritance
Inheritance: Acquiring properties from one class (Parent class) into another class (child class)
is called Inheritance.
Parent class is also called as Super class or Base class and Child class is
also called as Sub class or Derived class.
class Animal{
void eat(){
System.out.println("eating...");
}
}
class Dog extends Animal{
void bark()
System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep(){
System.out.println("weeping...");
}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}
}
Output:
weeping...
barking...
eating...
Hierarchical Inheritance : When two or more classes inherits a single class, it is known
as hierarchical inheritance. In the example given below, Dog and Cat classes inherits the
Animal class, so there is hierarchical inheritance.
class Animal{
void eat(){
System.out.println("eating...");
}
}
class Dog extends Animal{
void bark(){
System.out.println("barking...");
}
}
class Cat extends Animal{
void meow(){
System.out.println("meowing...");
}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}
}
Output:
meowing...
eating...
void showij() {
System.out.println("i and j: " + i + " " + j);
}
}
// Create a subclass by extending class A.
class B extends A {
int k;
void showk() {
System.out.println("k: " + k);
}
void sum() {
System.out.println("i+j+k: " + (i+j+k));
}
class SimpleInheritance {
public static void main(String[] args) {
A superOb = new A();
B subOb = new B();
Contents of subOb:
i and j: 7 8
k: 9
// Create a superclass.
class A {
int i; // default access
private int j; // private to A
void sum() {
total = i + j; // ERROR, j is not accessible here
}
}
class Access {
public static void main(String[] args) {
B subOb = new B();
subOb.setij(10, 12);
subOb.sum();
System.out.println("Total is " + subOb.total);
}
}
Here, the final version of the Box class developed in the preceding chapter will be extended to
include a fourth component called weight. Thus, the new class will contain a box’s width,
height, depth, and weight.
// This program uses inheritance to extend Box.class
Box {
double width;
double height;
double depth;
class DemoBoxWeight {
public static void main(String[] args) {
BoxWeight mybox1 = new BoxWeight(10, 20, 15, 34.3);
BoxWeight mybox2 = new BoxWeight(2, 3, 4, 0.076);
double vol;
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
System.out.println("Weight of mybox1 is " + mybox1.weight);
System.out.println();
vol = mybox2.volume();
System.out.println("Volume of mybox2 is " + vol);
System.out.println("Weight of mybox2 is " + mybox2.weight);
}
}
Output:
Volume of mybox1 is 3000.0
Weight of mybox1 is 34.3
2. Using super
In Java, the super keyword is used to refer to the immediate parent class object.
super has two general forms.
The first calls the superclass’ constructor.
The second is used to access a member of the superclass that has been hidden by a member
of a subclass.
Here, arg-list specifies any arguments needed by the constructor in the superclass. super( ) must always be the
first statement executed inside a subclass’ constructor.
// A complete implementation of BoxWeight.
class Box {
private double width;
private double height;
private double depth;
// default constructor
BoxWeight() {
super();
weight = -1;
}
class DemoSuper {
public static void main(String[] args) {
BoxWeight mybox1 = new BoxWeight(10, 20, 15, 34.3);
BoxWeight mybox2 = new BoxWeight(2, 3, 4, 0.076);
BoxWeight mybox3 = new BoxWeight(); // default
BoxWeight mycube = new BoxWeight(3, 2);
BoxWeight myclone = new BoxWeight(mybox1);
double vol;
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
System.out.println("Weight of mybox1 is " + mybox1.weight);
System.out.println();
vol = mybox2.volume();
System.out.println("Volume of mybox2 is " + vol);
System.out.println("Weight of mybox2 is " + mybox2.weight);
System.out.println();
vol = mybox3.volume();
System.out.println("Volume of mybox3 is " + vol);
System.out.println("Weight of mybox3 is " + mybox3.weight);
System.out.println();
vol = myclone.volume();
System.out.println("Volume of myclone is " + vol);
System.out.println("Weight of myclone is " + myclone.weight);
System.out.println();
vol = mycube.volume();
System.out.println("Volume of mycube is " + vol);
System.out.println("Weight of mycube is " + mycube.weight);
System.out.println();
}
}
Output:
Volume of mybox1 is 3000.0
Weight of mybox1 is 34.3
super.member
class B extends A {
int i; // this i hides the i in A
B(int a, int b) {
super.i = a; // i in A
i = b; // i in B
}
void show() {
System.out.println("i in superclass: " + super.i);
System.out.println("i in subclass: " + i);
}
}
class UseSuper {
public static void main(String[] args) {
B subOb = new B(1, 2);
subOb.show();
}
}
Output:
i in superclass: 1
i in subclass: 2
3. Creating a Multilevel Hierarchy
Given three classes called A, B, and C, C can be a subclass of B, which is a subclass of A. In this case, C
inherits all aspects of B and A. To see how a multilevel hierarchy can be useful, consider the following program.
In it, the subclass BoxWeight is used as a superclass to create the subclass called Shipment.
Shipment inherits all of the traits of BoxWeight and Box, and adds a field called cost, which holds the
cost of shipping such a parcel.
// Add weight.
class BoxWeight extends Box {
double weight; // weight of box
// construct clone of an object
BoxWeight(BoxWeight ob) { // pass object to constructor
super(ob);
weight = ob.weight;
}
// default constructor
BoxWeight() {
super();
weight = -1;
}
// default constructor
Shipment() {
super();
cost = -1;
}
class DemoShipment {
public static void main(String[] args) {
Shipment shipment1 =
new Shipment(10, 20, 15, 10, 3.41);
Shipment shipment2 =
new Shipment(2, 3, 4, 0.76, 1.28);
double vol;
vol = shipment1.volume();
System.out.println("Volume of shipment1 is " + vol);
System.out.println("Weight of shipment1 is "
+ shipment1.weight);
System.out.println("Shipping cost: $" + shipment1.cost);
System.out.println();
vol = shipment2.volume();
System.out.println("Volume of shipment2 is " + vol);
System.out.println("Weight of shipment2 is "
+ shipment2.weight);
System.out.println("Shipping cost: $" + shipment2.cost);
}
}
Output:
Volume of shipment1 is 3000.0
Weight of shipment1 is 10.0
Shipping cost: $3.41
class CallingCons {
public static void main(String[] args) {
C c = new C();
}
}
Output:
Inside A's constructor
Inside B's constructor
Inside C's constructor
5. Method Overriding
Method overriding occurs when a subclass provides a specific implementation for a method that is
already defined in its superclass.
Conditions for Method Overriding:
Same method name
Same method type signature (parameters and return type)
Key Point:
The version of the method defined by the superclass is hidden when called through the subclass.
// Method overriding.
class A {
int i, j;
A(int a, int b) {
i = a;
j = b;
}
// display i and j
void show() {
System.out.println("i and j: " + i + " " + j);
}
}
// Create a subclass by extending class A.
class B extends A {
int k;
Output:
This is k: 3
i and j: 1 2
class Dispatch {
public static void main(String[] args) {
A a = new A(); // object of type A
B b = new B(); // object of type B
C c = new C(); // object of type C
Output:
Figure(double a, double b) {
dim1 = a;
dim2 = b;
}
double area() {
System.out.println("Area for Figure is undefined.");return 0;
}
}
class FindAreas {
public static void main(String[] args) {
Figure f = new Figure(10, 10);
Rectangle r = new Rectangle(9, 5);
Triangle t = new Triangle(10, 8);
Figure figref;
figref = r;
System.out.println("Area is " + figref.area());
figref = t;
System.out.println("Area is " + figref.area());
figref = f;
System.out.println("Area is " + figref.area());
}
}
Output:
Inside Area for Rectangle.
Area is 45
Inside Area for Triangle.
Area is 40
Area for Figure is undefined.
Area is 0
7. Using Abstract Classes
Java abstract class is a class that can not be initiated by itself, it needs to be subclasses by
another class to use its properties.
An abstract class is declared using the “abstract” keyword in its class definition.
The main purpose of an abstract class is to provide a common structure for its subclasses,
ensuring that they implement certain essential methods.
An abstract class can also have constructors, data members, and static methods
Figure(double a, double b) {
dim1 = a;
dim2 = b;
}
// area is now an abstract method
abstract double area();
}
figref = r;
System.out.println("Area is " + figref.area());
figref = t;
System.out.println("Area is " + figref.area());
}
}
Output:
Inside Area for Rectangle.
Area is 45
Inside Area for Triangle.
Area is 40
class A {
final void meth() {
System.out.println("This is a final method.");
}
}
class B extends A {
void meth() { // ERROR! Can't override.
System.out.println("Illegal!");
}
}
However, it is critical to remember that, when using local variable type inference, the inferred type
of a variable is based on the declared type of its initializer.
Therefore, if the initializer is of the superclass type, that will be the inferred type of the variable.
It does not matter if the actual object being referred to by the initializer is an instance of a derived
class. For example, consider this program:
class MyClass {
// ...
}
class TypeInferenceAndInheritance {
// Return some type of MyClass object.
static MyClass getObj(int which) {
switch(which) {
case 0: return new MyClass();
case 1: return new FirstDerivedClass();
default: return new SecondDerivedClass();
}
}
There is one special class, Object, defined by Java. All other classes are subclasses of Object.
That is, Object is a superclass of all other classes. This means that a reference variable of type
Object can refer to an object of any other class.
Object defines the following methods, which means that they are available in every object.
Method Purpose
Object clone( ) Creates a new object that is the same as the object being
cloned.
boolean equals(Object object) Determines whether one object is equal to another.
void finalize( ) Called before an unused object is recycled. (Deprecated
by JDK 9.)
Class<?> getClass( ) Obtains the class of an object at run time.
int hashCode( ) Returns the hash code associated with the invoking
object.
void notify( ) Resumes execution of a thread waiting on the invoking
object.
void notifyAll( ) Resumes execution of all threads waiting on the invoking
object.
String toString( ) Returns a string that describes the object.
void wait( ) Waits on another thread of execution.
void wait(long milliseconds) void
wait(long milliseconds,
int nanoseconds)