Java M3
Java M3
class TestInheritance
{
INHERITANCE
public static void main(String args[])
1. INHERITANCE BASICS {
➢ Inheritance in Java is a mechanism in which one object acquires all the properties and
Dog d=new Dog();
behaviours of a parent object.
d.bark();
➢ Inheritance is an important pillar of OOP (Object-Oriented Programming). It is the
d.eat();
mechanism in Java by which one class is allowed to inherit the features (fields and
}
methods) of another class.
}
➢ Inheritance represents the IS-A relationship, also known as parent-child relationship.
➢ In Java, Inheritance means creating new classes based on existing ones. 1.1 Member Access and Inheritance
➢ A class that inherits from another class can reuse the methods and fields of that class. Although a subclass includes all of the members of its superclass, it cannot access those
➢ In addition, you can add new fields and methods to your current class as well. members of the superclass that have been declared as private.
Example:
The extends keyword is used for inheritance in Java. Using the extends keyword
indicates you are derived from an existing class. In other words, “extends” refers to /* In a class hierarchy, private members remain private to their class. This program contains an
increased functionality.
error and will not compile. */
Syntax : class A
RAMYA R, Assistant Professor KSIT, Dept. of CSE RAMYA R, Assistant Professor KSIT, Dept. of CSE
3 Module -3:BCS306A 4 Module -3:BCS306A
subOb.sum();
2. USING SUPER
System.out.println("Total is " + subOb.total); ➢ Whenever the derived class inherits the base class features, there is a possibility that
base class features are similar to derived class features and JVM gets an ambiguity.
}}
➢ To overcome this, super is used to refer super class properties.
1.2 A super class variable can reference a subclass object: ➢ The super keyword in java is a reference variable that is used to refer parent class.
A reference variable of a super class can be assigned a reference to any subclass derived ➢ The keyword “super” came into the picture with the concept of Inheritance. It is majorly
from that super class. used in the following contexts:
Ex:
– super is used to refer immediate parent class instance variable.
class A
{ super.parent_instance_variable_name;
RAMYA R, Assistant Professor KSIT, Dept. of CSE RAMYA R, Assistant Professor KSIT, Dept. of CSE
5 Module -3:BCS306A 6 Module -3:BCS306A
Usage 1. - Using super to refer super class property Usage 2. - super is used to invoke immediate parent class method
{ {
} {
{ }
int speed=100; }
{ {
} }
{ {
public static void main(String args[]) message();//will invoke or call current class message() method
b.display(); }
} class SuperClassMethod
} {
RAMYA R, Assistant Professor KSIT, Dept. of CSE RAMYA R, Assistant Professor KSIT, Dept. of CSE
7 Module -3:BCS306A 8 Module -3:BCS306A
f.display(); }
} }
} Output:
Usage 3. - super is used to invoke immediate parent class constructor Vehicle is created
RAMYA R, Assistant Professor KSIT, Dept. of CSE RAMYA R, Assistant Professor KSIT, Dept. of CSE
9 Module -3:BCS306A 10 Module -3:BCS306A
obj.funcB(); B() {
obj.funcC(); System.out.println("Inside B's constructor.");
} }}
} Create another subclass by extending B.
Output class C extends B {
This is class A C()
This is class B {
This is class C System.out.println("Inside C's constructor.");
}}
Given a subclass called B and a superclass called A, is A’s constructor executed before B’s, Inside A's constructor
RAMYA R, Assistant Professor KSIT, Dept. of CSE RAMYA R, Assistant Professor KSIT, Dept. of CSE
11 Module -3:BCS306A 12 Module -3:BCS306A
//defining the same method as in the parent class System.out.println("Inside B's m1 method");
void run(){System.out.println("Bike is running safely");}
}}
class C extends A
public static void main(String args[]){
Bike2 obj = new Bike2(); //creating object {
Dynamic Method Dispatch in Java is the process by which a call to an overridden method is {
resolved at runtime (during the code execution). The concept of method overriding is the way
public static void main(String args[])
to attain runtime polymorphism in Java.
{
// A Java program to illustrate Dynamic Method
A a = new A(); // object of type A
// Dispatch using hierarchical inheritance
B b = new B(); // object of type B
class A
C c = new C(); // object of type C
{
A ref; // obtain a reference of type A
void m1()
ref = a; // ref refers to an A object
{
ref.m1(); // calling A's version of m1()
System.out.println("Inside A's m1 method");
ref = b; // now ref refers to a B object
}}
ref.m1(); // calling B's version of m1()
RAMYA R, Assistant Professor KSIT, Dept. of CSE RAMYA R, Assistant Professor KSIT, Dept. of CSE
13 Module -3:BCS306A 14 Module -3:BCS306A
RAMYA R, Assistant Professor KSIT, Dept. of CSE RAMYA R, Assistant Professor KSIT, Dept. of CSE
15 Module -3:BCS306A 16 Module -3:BCS306A
➢ Note that it is not necessary to declare final methods in the initial stage of inheritance Output
(base class always).
Error
➢ We can declare a final method in any subclass for which we want that if any other class
extends this subclass, then it must follow the same implementation of the method as in Use 3: To prevent inheritance
that subclass.
final class Vehicle
Uses of Final:
{
Final can be used in three ways:
void run()
• To prevent modifications to the instance variable
{
• To Prevent method overriding
System.out.println("running");
• To prevent inheritance
}}
Use 2: To prevent method overriding
class Bike extends Vehicle
class Vehicle
{
{
void run()
final void run()
{
{
System.out.println("running safely with 100kmph");
System.out.println("running");
}}
}}
class FinalClass
class Bike extends Vehicle
{
{
public static void main(String args[])
void run()
{
{
Bike b= new Bike();
System.out.println("running safely with 100kmph");
b.run();
}}
}
class FinalMethod
}
{
Output:
public static void main(String args[])
Class Bike extends vehicle
{
Bike b= new Bike();
b.run();
}
}
RAMYA R, Assistant Professor KSIT, Dept. of CSE RAMYA R, Assistant Professor KSIT, Dept. of CSE
17 Module -3:BCS306A 18 Module -3:BCS306A
LOCAL VARIABLE TYPE INFERENCE AND INHERITANC protected Object clone() throws creates and returns the exact copy (clone) of this
Local variable type inference is a feature in Java 10 that allows the developer to skip the type CloneNotSupportedException object.
declaration associated with local variables (those defined inside method definitions, public String toString() returns the string representation of this object.
initialization blocks, for-loops, and other blocks like if-else), and the type is inferred by the
public final void notify() wakes up single thread, waiting on this object's
JDK. monitor.
The following was the only correct syntax: public final void notifyAll() wakes up all the threads, waiting on this object's
monitor.
Class_name variable_name=new Class_name(arguments);
public final void wait(long timeout)throws causes the current thread to wait for the specified
// Sample Java local variable declaration InterruptedException milliseconds, until another thread notifies (invokes
notify() or notifyAll() method).
import java.util.ArrayList;
import java.util.List; public final void wait(long timeout,int causes the current thread to wait for the specified
nanos)throws InterruptedException milliseconds and nanoseconds, until another thread
class A { notifies (invokes notify() or notifyAll() method).
public static void main(String a[])
public final void wait()throws causes the current thread to wait, until another thread
{ InterruptedException notifies (invokes notify() or notifyAll() method).
List<Map> data = new ArrayList<>();
protected void finalize()throws Throwable is invoked by the garbage collector before object is
} being garbage collected.
}
Method Description
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.
public int hashCode() returns the hashcode number for this object.
public boolean equals(Object obj) compares the given object to this object.
RAMYA R, Assistant Professor KSIT, Dept. of CSE RAMYA R, Assistant Professor KSIT, Dept. of CSE
19 Module -3:BCS306A 20 Module -3:BCS306A
interface Moveable
1. INTERFACES {
➢ The interface in Java is a mechanism to achieve abstraction.
➢ There can be only abstract methods in the Java interface, not the method body. It is int AVG_SPEED=30;
used to achieve abstraction and multiple inheritances in Java using Interface. void Move();
➢ In other words, you can say that interfaces can have abstract methods and variables. It
}
cannot have a method body.
➢ Java Interface also represents the IS-A relationship. class Move implements Moveable
} }
Implementing Interfaces:
class Vehicle
• 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
public static void main (String[] arg)
the methods defined by the interface.
{
• The general form of a class that includes the implements clause looks like this:
Move m = new Move();
class classname [extends superclass] [implements interface1 [,interface2...]]
m.Move();
{
}
// class-body
}
}
Example 2: Write a java program to implement interface.
• If a class implements more than one interface, the interfaces are separated with a comma.
interface Teacher
• 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
void display1();
RAMYA R, Assistant Professor KSIT, Dept. of CSE RAMYA R, Assistant Professor KSIT, Dept. of CSE
21 Module -3:BCS306A 22 Module -3:BCS306A
} }
interface Student
void display2(); We can declare variables as object references that use an interface rather than a class type. Any
instance of any class that implements the declared interface can be referred to by such a
}
variable. When you call a method through one of these references, the correct version will be
class College implements Teacher, Student called based on the actual instance of the interface being referred to. This is one of the key
RAMYA R, Assistant Professor KSIT, Dept. of CSE RAMYA R, Assistant Professor KSIT, Dept. of CSE
23 Module -3:BCS306A 24 Module -3:BCS306A
Variables in Interfaces: One interface can inherit another by use of the keyword extends.
We can use interfaces to import shared constants into multiple classes by simply declaring an The syntax is the same as for inheriting classes. When a class implements an interface that
interface that contains variables that are initialized to the desired values. inherits another interface, it must provide implementations for all methods defined within the
interface inheritance chain.
When we include that interface in a class (that is, when you “implement” the interface), all of
those variable names will be in scope as constants. DEFAULT INTERFACE METHODS
If an interface contains no methods, then any class that includes such an interface doesn’t Default methods enable you to add new functionality to the interfaces of your libraries and
actually implement anything. Itis as if that class were importing the constant fields into the ensure binary compatibility with code written for older versions of those interfaces.
class name space as final variables.
If we have an implemented method inside an interface with default keyword, then we will call
Example: Java program to demonstrate variables in interface. it as a Default method. We also call it defender method or virtual extension method.
{ interface Human {
int i=100; }
Implementing classes are free to provide their own implementation of the default method. If
}
the implementing class doesn’t override the default method, it means that the class doesn’t
need that functionality in it.
class Test implements left,right
PRIVATE INTERFACE METHODS
{
➢ We can create private methods inside an interface. Interface allows us to declare private
public static void main(String args[]) methods that help to share common code between non-abstract methods.
{
// private methods in interfaces
System.out.println(left.i);//10 will be printed
interface Sayable{
System.out.println(right.i);//100 will be printed*/
default void say() {
}}
saySomething();
RAMYA R, Assistant Professor KSIT, Dept. of CSE RAMYA R, Assistant Professor KSIT, Dept. of CSE
25 Module -3:BCS306A 26 Module -3:BCS306A
}
6) An abstract class can extend An interface can extend another Java interface only.
another Java class and implement
// Private method inside interface multiple Java interfaces.
private void saySomething() { 7) An abstract class can be extended An interface can be implemented using keyword
using keyword "extends". "implements".
System.out.println("Hello... I'm private method");
8) A Java abstract class can have Members of a Java interface are public by default.
} class members like private, protected,
etc.
}
9)Example: Example:
public class PrivateInterface implements Sayable { public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
public static void main(String[] args) { } }
s.say();
}}
Output:
1) Abstract class can have abstract Interface can have only abstract methods. Since Java
and non-abstract methods. 8, it can have default and static methods also.
3) Abstract class can have final, non- Interface has only static and final variables.
final, static and non-static
variables.
4) Abstract class can provide the Interface can't provide the implementation of
implementation of interface. abstract class.
5) The abstract keyword is used to The interface keyword is used to declare interface.
declare abstract class.
RAMYA R, Assistant Professor KSIT, Dept. of CSE RAMYA R, Assistant Professor KSIT, Dept. of CSE