Unit 2 Oops
Unit 2 Oops
➔Inheritance in Java
Inheritance in Java is a mechanism in which one object acquires all the properties
and behaviors of a parent object. It is an important part of OOPs (Object Oriented
programming system).
The idea behind inheritance in Java is that you can create new classes that are built
upon existing classes. When you inherit from an existing class, you can reuse
methods and fields of the parent class. Moreover, you can add new methods and
fields in your current class also.
Inheritance represents the IS-A relationship which is also known as a parent-
child relationship.
Why use inheritance in java?
• For Method Overriding (so runtime polymorphism can be achieved).
• For Code Reusability.
Important Terminologies Used in Java Inheritance
Class: Class is a set of objects which shares common characteristics/ behavior and
common properties/ attributes. Class is not a real-world entity. It is just a template
or blueprint or prototype from which objects are created.
Super Class/Parent Class: The class whose features are inherited is known as a
superclass (or a base class or a parent class).
Sub Class/Child Class: The class that inherits the other class is known as a subclass
(or a derived class, extended class, or child class). The subclass can add its own
fields and methods in addition to the superclass fields and methods.
How to Use Inheritance in Java?
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
increased functionality.
Syntax :
class sub-class extends super-class
{
//methods and fields
}
Example:
class Employee
{
float salary=40000;
}
class Programmer extends Employee
{
int bonus=10000;
public static void main(String args[])
{
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
Example:
What You Can Do in a Subclass?
A subclass inherits all of the public and protected members of its parent, no matter
what package the subclass is in. If the subclass is in the same package as its parent,
it also inherits the package-private members of the parent. You can use the inherited
members as is, replace them, hide them, or supplement them with new members:
• The inherited fields can be used directly, just like any other fields.
• You can declare a field in the subclass with the same name as the one in the
superclass, thus hiding it (not recommended).
• You can declare new fields in the subclass that are not in the superclass.
• The inherited methods can be used directly as they are.
• You can write a new instance method in the subclass that has the same
signature as the one in the superclass, thus overriding it.
• You can write a new static method in the subclass that has the same
signature as the one in the superclass, thus hiding it.
• You can declare new methods in the subclass that are not in the superclass.
• You can write a subclass constructor that invokes the constructor of the
superclass, either implicitly or by using the keyword super.
Private Members in a Superclass
A subclass does not inherit the private members of its parent class. However, if the
superclass has public or protected methods for accessing its private fields, these can
also be used by the subclass.
A nested class has access to all the private members of its enclosing class—both
fields and methods. Therefore, a public or protected nested class inherited by a
subclass has indirect access to all of the private members of the superclass.
➔Method Overriding
Whatever the parent has by default available to the child class through inheritance,
If the child class is not satisfied with the parent class method implementation, the
child is allowed to overwrite that parent class method to provide its specific
implementation. This concept is nothing but “overriding”.
public class P
{
public void property()
{
System.out.println("Land, gold, cash");
}
public void marry()
{
System.out.println("Keerthi");
}
}
public class C extends P
{
public void marry()
{
System.out.println("Priyanka");
}
}
public class Test
{
public static void main(String[] args)
{
P p1 = new P();
p1.marry(); //Keerthi
C c1 = new C();
c1.marry(); //Priyanka
P p2 = new C();
p2.marry(); //Priyanka
}
}
Overriding method resolution will take care of by JVM based on the run time Object.
Hence overriding is considered as run time polymorphism or dynamic
polymorphism, or late binding.
Rules for overriding:
• Only inherited methods can be overridden.
• Final and static methods cannot be overridden.
• The overriding method must have same argument list.
• The overriding method must have same return type (or subtype).
• The overriding method must not have more restrictive access modifier.
• The overriding method must not throw new or broader checked exceptions
• Use the super keyword to invoke the overridden method from a subclass.
• Constructors cannot be overridden.
• Abstract methods must be overridden by the first concrete (non-abstract)
subclass.
• A static method in a subclass may hide another static one in a superclass, and
that’s called hiding.
Overriding in static methods:
1. A static method can’t be overridden as non-static. Similarly, a non-static method
can’t be overridden as static method.
class P
{
public static void m1()
{
}
}
class C extends P
{
public void m1()
{
}
}
m1() in C cannot override m1() in P; overridden method is static
2. If both parent and child class methods are static, there is no compile-time or run
time error. It seems that overriding happens, but it is not overriding this concept is
called “method hiding.” All the rules of method hiding are exactly similar to
overriding, except both methods are declared as static.
Example: Method overriding
class Animal
{
public void display()
{
System.out.println("I am an animal");
}
}
class Dog extends Animal
{
public void display()
{
System.out.println("I am a dog");
}
public void printMessage()
{
System.out.println(“Hello”);
}
}
class Main
{
public static void main(String[] args)
{
Dog dog1 = new Dog();
dog1.display();
}
}
Output
I am a dog
Since display() is defined in both the classes, the method of subclass Dog overrides
the method of superclass Animal. Hence, the display() of the subclass is called.
3. The super keyword in Java is used in subclasses to access superclass members
(attributes, constructors and methods).
Uses of super keyword:
• To call methods of the superclass that is overridden in the subclass.
• To access attributes (fields) of the superclass if both superclass and subclass
have attributes with the same name.
• To explicitly call superclass no-arg (default) or parameterized constructor
from the subclass constructor.
Let’s understand each of these uses.
class Main
{
public static void main(String[] args)
{
Dog dog1 = new Dog();
dog1.printType();
}
}
Output:
I am a mammal
I am an animal
class Main
{
public static void main(String[] args)
{
Dog dog1 = new Dog();
}
}
Output
Type: Animal
I am a dog
If a class contains an abstract method, then the class should be declared abstract.
Otherwise, it will generate an error.
class TestBank
{
public static void main(String args[])
{
Bank b;
b=new SBI();
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %);
b=new PNB();
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %);
}
}
➔Interfaces
An interface may be a collection of abstract method, fields with final and static
modifiers, default method, and static method.
• Like abstract classes, interfaces cannot be used to create objects Interface
abstract methods do not have a body - the body is provided by the "implement"
class
• On implementation of an interface, you must override all of its methods
• Interface methods are by default abstract and public
• Interface attributes are by default public, static and final
• An interface cannot contain a constructor
• All the methods inside an interface are implicitly public and all fields are
implicitly public static final.
• With the release of Java 8, we can now add methods with implementation
inside an interface. These methods are called default methods.
• The Java 8 also added another feature to include static methods inside an
interface.
• With the release of Java 9, private methods are also supported in interfaces.
interface Language
{
void getName(String name);
}
class ProgLang implements Language
{
public void getName(String name)
{
System.out.println("Programming Language: " + name);
}
}
class Main
{
public static void main(String[] args)
{
ProgLang language = new ProgLang();
language.getName("Java");
}
}
extends vs implements
interface A
{
}
interface B
{
}
// Extending Multiple Interfaces
interface C extends A,B
{
}
// implementing Multiple Interfaces
class D implements A,B
{
}
interface Polygon
{
void getArea();
default void getSides()
{
System.out.println("I can get sides of a polygon.");
}
}
interface Polygon {
void staticMethod(){..}
}
Similarly, we can have the class use the default methods defined within
the Alarm interface: