Mod 3 Notes
Mod 3 Notes
Module 3
Syllabus
Anupriya A G Page|1
Dept. of CSE(AIML), RLJIT
OBJECT ORIENTED PROGRAMMING WITH JAVA BCS306A
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. Super class do not have knowledge of Sub class. But
Sub class is having knowledge of Parent Class and Its own class.
The Acquiring properties from Parent class to child class are:
Instance variables of Super class can be accessible inside subclass
Methods of super class can be accessible inside sub class.
Anupriya A G Page|2
Dept. of CSE(AIML), RLJIT
OBJECT ORIENTED PROGRAMMING WITH JAVA BCS306A
}
Output: Programmer salary is:40000.0
Bonus of programmer is:10000
The relationship between the two classes is Programmer IS-A Employee. It means that
Programmer is a type of Employee.
Anupriya A G Page|3
Dept. of CSE(AIML), RLJIT
OBJECT ORIENTED PROGRAMMING WITH JAVA BCS306A
class Animal{
void eat(){
System.out.println("eating...");
}
}
class Dog extends Animal{
void bark(){
System.out.println("barking...");
}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}
}
Output:
barking...
eating...
Multilevel Inheritance Example: When there is a chain of inheritance, it is known as multilevel
inheritance. As you can see in the example given below, BabyDog class inherits the Dog class
which again inherits the Animal class, so there is a multilevel inheritance.
class Animal{
void eat(){
System.out.println("eating...");
}
}
Anupriya A G Page|4
Dept. of CSE(AIML), RLJIT
OBJECT ORIENTED PROGRAMMING WITH JAVA BCS306A
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 Example: 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(){
Anupriya A G Page|5
Dept. of CSE(AIML), RLJIT
OBJECT ORIENTED PROGRAMMING WITH JAVA BCS306A
System.out.println("barking...");
}
}
Inheritance Basics: To inherit a class, you simply incorporate the definition of one class into
another by using the extends keyword. To see how, let’s begin with a short example. The following
program creates a superclass called A and a subclass called B. Notice how the keyword extends
is used to create a subclass of A.
// A simple example of inheritance.Create a superclass.
class A {
int i, j;
void showij() {
System.out.println("i and j: " + i + " " + j);
}
}
// Create a subclass by extending class A.
class B extends A {
int k;
Anupriya A G Page|6
Dept. of CSE(AIML), RLJIT
OBJECT ORIENTED PROGRAMMING WITH JAVA BCS306A
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();
// The superclass may be used by itself.
superOb.i = 10;
superOb.j = 20;
System.out.println("Contents of superOb: ");
superOb.showij();
System.out.println();
/* The subclass has access to all public members of its superclass. */
subOb.i = 7;
subOb.j = 8;
subOb.k = 9;
System.out.println("Contents of subOb: ");
subOb.showij();
subOb.showk();
System.out.println();
System.out.println("Sum of i, j and k in subOb:");
subOb.sum();
}
}
Anupriya A G Page|7
Dept. of CSE(AIML), RLJIT
OBJECT ORIENTED PROGRAMMING WITH JAVA BCS306A
Using super: The super keyword in java is a reference variable which is used to refer
immediate parent class object. Whenever you create the instance of subclass, an instance of
parent class is created implicitly which is referred by super reference variable.
Usage of java super Keyword
1. super can be used to refer immediate parent class instance variable.
2. super can be used to invoke immediate parent class method.
3. super() can be used to invoke immediate parent class constructor.
1. super is used to refer immediate parent class instance variable. We can use super
keyword to access the data member or field of parent class. It is used if parent class and child
class have same fields. Sub-class variable hides the super-class variable in class sub-class.
class Animal{
String color="white";
}
class Dog extends Animal{
String color="black"; //this hides color in Animal
void printColor(){
System.out.println(color); //prints color of Dog class
System.out.println(super.color); //prints color ofAnimal class
}
}
class Mainclass{
public static void main(String[ ] args){
Dog d=new Dog();
d.printColor();
}
}
Output: black
white
class A {
int i;
private int j;
A(int a, int b) {
i=a;
j=b;
Anupriya A G Page|8
Dept. of CSE(AIML), RLJIT
OBJECT ORIENTED PROGRAMMING WITH JAVA BCS306A
}
void addij(){
int k=i+j;
System.out.println("(i+j=)"+k);
}
}
class B extends A {
int k;
B(int a, int b, int c){
super(a,b);
k=c;
}void addik() {
System.out.println("i: " + i);
//System.out.println("j: " + j); //Error j is private cannot access j in B
System.out.println("k: " + k);
int c=i+k;
System.out.println("i+k="+c);
}
}
class Mainclass{
public static void main(String[ ] args){
B b=new B(1,2,3);
b.addij();
b.addik();
}
}
Output: (i+j=)3
i: 1
k: 3
i+k=4
2. super is used to invoke super-class(parent class) method.. The super keyword can
also be used to invoke the parent class method when parent class method and child class
method names are same in other words method is overridden.
Let's see a simple example:
class Animal{
void eat(){
System.out.println("All Animals can eat...");
}
}
class Dog extends Animal{
Anupriya A G Page|9
Dept. of CSE(AIML), RLJIT
OBJECT ORIENTED PROGRAMMING WITH JAVA BCS306A
void eat(){
System.out.println("eating bread...");
}
void bark(){
System.out.println("barking...");
}
void work(){
super.eat();
bark();
}
}
class Mainclass{
public static void main(String args[]){
Dog d=new Dog();
d.work();
}
}
Creating a Multilevel Hierarchy: The level of the inheritance is two or more then we can call it
as multilevel inheritance. you 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. 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.
class Box {
private double width;
private double height;
private double depth;
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
double volume() {
return width * height * depth;
}
}
class BoxWeight extends Box {
Anupriya A G P a g e | 10
Dept. of CSE(AIML), RLJIT
OBJECT ORIENTED PROGRAMMING WITH JAVA BCS306A
double weight;
BoxWeight(double w, double h, double d, double m) {
super(w, h, d);
weight = m;
}
}
class Shipment extends BoxWeight {
double cost;
Shipment(double w, double h, double d,double m, double c) {
super(w, h, d, m);
cost = c;
}
}
class Mainclass{
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();
}
}
When Constructors Are Called: When a class hierarchy is created, in what order are the
constructors for the classes that make up the hierarchy called? 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 or parameterless constructor of each superclass will be
executed. The following program illustrates when constructors are executed:
// Demonstrate when constructors are called.
// Create a super class.
class A {
A() {
System.out.println("Inside A's constructor.");
}
}
// Create a subclass by extending class A.
Anupriya A G P a g e | 11
Dept. of CSE(AIML), RLJIT
OBJECT ORIENTED PROGRAMMING WITH JAVA BCS306A
class B extends A {
B() {
System.out.println("Inside B's constructor.");
}
}
// Create another subclass by extending B.
class C extends B {
C() {
System.out.println("Inside C's constructor.");
}
}
class CallingCons {
public static void main(String args[]) {
C c = new C();
}
}
The output from this program is shown here:
Inside A’s constructor
Inside B’s constructor
Inside C’s constructor
Method Overriding in Java: If subclass (child class) has the same method as declared in the
parent class, it is known as method overriding in java. In other words, If subclass provides
the specific implementation of the method that has been provided by one of its parent class,
it is known as method overriding.
class Bank{
int getRateOfInterest(){
return 0;
}
Anupriya A G P a g e | 12
Dept. of CSE(AIML), RLJIT
OBJECT ORIENTED PROGRAMMING WITH JAVA BCS306A
}
class SBI extends Bank{
int getRateOfInterest(){
return 8;
}
}
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.
Anupriya A G P a g e | 13
Dept. of CSE(AIML), RLJIT
OBJECT ORIENTED PROGRAMMING WITH JAVA BCS306A
Anupriya A G P a g e | 14
Dept. of CSE(AIML), RLJIT
OBJECT ORIENTED PROGRAMMING WITH JAVA BCS306A
2. method
3. class
final variable: There is a final variable speedlimit, we are going to change the value of this
variable, but It can't be changed because final variable once assigned a value can never be
changed.
class Bike9{
final int speedlimit=90; //final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}
} Output: Compile Time Error
Java final method: If you make any method as final, you cannot override it.
class Bike{
final void run(){
System.out.println("running");
}
}
Anupriya A G P a g e | 15
Dept. of CSE(AIML), RLJIT
OBJECT ORIENTED PROGRAMMING WITH JAVA BCS306A
class MainClass{
public static void main(String args[]){
Honda honda= new Honda();
honda.run();
}
} Output: Compile Time Error
Java final class: If you make any class as final, you cannot inherit it.
final class Bike{
int add(){
return 10;
}
}
class Honda1 extends Bike{
void run(){
System.out.println("running safely with 100kmph");
}
class MainClass{
public static void main(String args[]){
Honda1 honda= new Honda1();
honda.run();
}
}
Output: Compile Time Error
Abstract Classes: There are situations in which you will want to define a super-class that declares
the structure of a given abstraction without providing a complete implementation of every method.
That is, sometimes you will want to create a super-class that only defines a generalized form that
will be shared by all of its subclasses, leaving it to each subclass to fill in the details. To declare an
abstract method, use this general form:
abstract type name(parameter-list);
As you can see,
no method body is present.
Any class that contains one or more abstract methods must also be declared abstract. To
declare a class abstract, you simply use the abstract keyword in front of the class
keyword at the beginning of the class declaration.
Anupriya A G P a g e | 16
Dept. of CSE(AIML), RLJIT
OBJECT ORIENTED PROGRAMMING WITH JAVA BCS306A
There can be no objects of an abstract class. That is, an abstract class cannot be directly
instantiated with the new operator. Such objects would be useless, because an abstract
class is not fully defined.
Anupriya A G P a g e | 17
Dept. of CSE(AIML), RLJIT
OBJECT ORIENTED PROGRAMMING WITH JAVA BCS306A
figref = r;
System.out.println("Area is " + figref.area());
figref = t;
System.out.println("Area is " + figref.area());
}
}
An interface is defined much like a class. This is the general form of an interface:
access interface name {
type final-varname1 = value;
type final-varname2 = value;
type final-varnameN = value;
return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
Anupriya A G P a g e | 18
Dept. of CSE(AIML), RLJIT
OBJECT ORIENTED PROGRAMMING WITH JAVA BCS306A
// ...
return-type method-nameN(parameter-list);
Anupriya A G P a g e | 19
Dept. of CSE(AIML), RLJIT
OBJECT ORIENTED PROGRAMMING WITH JAVA BCS306A
6 implements printable{
public void print(){
Java System.out.println("Hello");
Interfa }
ce public static void
Examp
main(String args[]){ A6
le
obj = new A6();
interface obj.print();
printable // obj.x++; cannot change the value of the x because it is final
{ }
i }
n
Multtiple inheritance in Java by interface
interfxace Printable{
= void print();
1 }
0
in0terface Showable{
; void show();
v }
o class A7 implements Printable,Showable{
p public void print(){
r System.out.println("Hello
i ");
n }
t public void show(){
( System.out.println("Welc
) ome");
; }
} public static void main(String
c args[]){ A7 obj = new
l A7();
a obj.print();
s obj.show();
s }
A
Anupriya A G P a g e | 20
Dept. of CSE(AIML), RLJIT
OBJECT ORIENTED PROGRAMMING WITH JAVA BCS306A
} he non-abstract methods which are defined inside the interface are called as Default
Interface methods. The concept of default method is used to define a method with default
implementation. You can override default method also to provide more specific
D implementation for the method.
e
f interface Sayable{
a default void say(){
u System.out.println("Hello, this is default method");
l
t }
I void sayMore(String msg);
n }
t
public class DefaultMethods implements Sayable{
e
r public void sayMore(String msg){ // implementing
f abstract method System.out.println(msg);
a }
c
e
M
e
t
h
o Ex
d a
s m
pl
:
e:
T
Anupriya A G P a g e | 21
Dept. of CSE(AIML), RLJIT
OBJECT ORIENTED PROGRAMMING WITH JAVA BCS306A
p s) { DefaultMethods dm = new
u DefaultMethods(); dm.say(); //
b calling default method
l dm.sayMore("Work is worship"); // calling abstract method
i
c
s }
Out tput:
a
t
i
c
v
o
i
d
m
a
i
n
(
S
t
r
i
n
g
[
]
a
r
g
Anupriya A G P a g e | 22
Dept. of CSE(AIML), RLJIT
OBJECT ORIENTED PROGRAMMING WITH JAVA BCS306A
Static Methods inside Interface: You can also define static methods inside the interface. Static
methods are used to define utility methods. Static methods are nowhere related to objects. We can
access static methods using Interface name. The following example explain, how to implement
static method in interface?
interface Sayable{
static void sayLouder(String msg){
System.out.println(msg);
}
}
public class DefaultMethods implements Sayable{
public static void main(String[] args) {
Sayable.sayLouder("Helloooo..."); // calling static method
}
}
Output: Helloooo...
Private Interface Methods: 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();
Anupriya A G P a g e | 23
Dept. of CSE(AIML), RLJIT
OBJECT ORIENTED PROGRAMMING WITH JAVA BCS306A
s.say();
}
}
Output: Hello... I'm private method
Object class: The Object class is the parent class of all the classes in java by default. The Object
class is beneficial if you want to refer any object whose type you don't know. Notice that parent
class reference variable can refer the child class object, know as upcasting. The Object class
provides some common behaviors to all the objects such as object can be compared, object can be
cloned, object can be notified etc.
1 public final Class getClass() Returns the Class class object of this object.
The Class class can further be used to get the
metadata of this class.
2 public int hashCode() returns the hashcode number for this object.
3 public boolean equals(Object obj) compares the given object to this object.
public final void wait()throws causes the current thread to wait, until another
8 InterruptedException thread notifies (invokes notify() or notifyAll()
method).
public final void wait(long timeout,int auses the current thread to wait for the
9 nanos)throws InterruptedException specified milliseconds and nanoseconds, until
another thread notifies (invokes notify() or
notifyAll() method).
Anupriya A G P a g e | 24
Dept. of CSE(AIML), RLJIT
OBJECT ORIENTED PROGRAMMING WITH JAVA BCS306A
protected Object clone() throws creates and returns the exact copy (clone) of
10 CloneNotSupportedException this object.
Anupriya A G P a g e | 25
Dept. of CSE(AIML), RLJIT