0% found this document useful (0 votes)
13 views

Unit 2 Oops

The document discusses inheritance in Java, including its definition and purpose, important terminology like superclass and subclass, how to implement inheritance using the 'extends' keyword, what can be done in a subclass, private members in a superclass, types of inheritance, method overriding including its rules and uses of the 'super' keyword, and an example of method overriding.

Uploaded by

Harendra Tomar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Unit 2 Oops

The document discusses inheritance in Java, including its definition and purpose, important terminology like superclass and subclass, how to implement inheritance using the 'extends' keyword, what can be done in a subclass, private members in a superclass, types of inheritance, method overriding including its rules and uses of the 'super' keyword, and an example of method overriding.

Uploaded by

Harendra Tomar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

UNIT - II

➔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.

➔Types of inheritance in java


On the basis of class, there can be three types of inheritance in java: single,
multilevel and hierarchical.
In java programming, multiple and hybrid inheritance is supported through
interface only.

➔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.

1. Access Overridden Methods of the superclass


If methods with the same name are defined in both superclass and subclass, the
method in the subclass overrides the method in the superclass. This is called method
overriding.
Example: super to Call Superclass Method
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");
super.display();
}
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
I am an animal
2. Access Attributes of the Superclass
The superclass and subclass can have attributes with the same name. We use
the super keyword to access the attribute of the superclass.
Example: Access superclass attribute
class Animal
{
protected String type="animal";
}
class Dog extends Animal
{
public String type="mammal";
public void printType()
{
System.out.println("I am a " + type);
System.out.println("I am an " + super.type);
}
}

class Main
{
public static void main(String[] args)
{
Dog dog1 = new Dog();
dog1.printType();
}
}
Output:
I am a mammal
I am an animal

Inside the printType() function,


type refers to the attribute of the subclass Dog.
super.type refers to the attribute of the superclass Animal.

3. Use of super() to access superclass constructor


As we know, when an object of a class is created, its default constructor is
automatically called.
To explicitly call the superclass constructor from the subclass constructor, we
use super(). It's a special form of the super keyword.
super() can be used only inside the subclass constructor and must be the first
statement.
Example: Use of super()
class Animal
{
Animal()
{
System.out.println("I am an animal");
}
}
class Dog extends Animal
{
Dog()
{
super();
System.out.println("I am a dog");
}
}
class Main
{
public static void main(String[] args)
{
Dog dog1 = new Dog();
}
}
Output
I am an animal
I am a dog
Here, when an object dog1 of Dog class is created, it automatically calls the default
or no-arg constructor of that class.
Inside the subclass constructor, the super() statement calls the constructor of the
superclass and executes the statements inside it. Hence, we get the output I am an
animal.
The flow of the program then returns back to the subclass constructor and executes
the remaining statements. Thus, I am a dog will be printed.
However, using super() is not compulsory. Even if super() is not used in the
subclass constructor, the compiler implicitly calls the default constructor of the
superclass.
So, why use redundant code if the compiler automatically invokes super()?
• It is required if the parameterized constructor (a constructor that takes
arguments) of the superclass has to be called from the subclass constructor.
• The parameterized super() must always be the first statement in the body of
the constructor of the subclass, otherwise, we get a compilation error.
Example: Call Parameterized Constructor Using super()
class Animal
{
Animal()
{
System.out.println("I am an animal");
}
Animal(String type)
{
System.out.println("Type: "+type);
}
}
class Dog extends Animal
{
Dog()
{
super("Animal");
System.out.println("I am a dog");
}
}

class Main
{
public static void main(String[] args)
{
Dog dog1 = new Dog();
}
}
Output
Type: Animal
I am a dog

• The compiler can automatically call the no-arg constructor. However, it


cannot call parameterized constructors.
• If a parameterized constructor has to be called, we need to explicitly define it
in the subclass constructor.
Note that in the above example, we explicitly called the parameterized
constructor super("Animal"). The compiler does not call the default constructor of
the superclass in this case.
Constructor in subclass
• subclasses do not inherit constructors from the superclass.
• In Java, the superclass constructor can be called from the first line of a
subclass constructor by using the special keyword super() and passing
appropriate parameters,
class Person
{
private String name;
public Person(String theName)
{
this.name = theName;
}

public String getName()


{
return name;
}
public boolean setName(String theNewName)
{
if (theNewName != null)
{
this.name = theNewName;
return true;
}
return false;
}
}
public class Employee extends Person
{
private int id;
public static int nextId = 1;
public Employee(String theName)
{
super(theName);
id = nextId;
nextId++;
}
public int getId()
{
return id;
}

public static void main(String[] args)


{
Employee emp = new Employee("Dani");
System.out.println(emp.getName());
System.out.println(emp.getId());
}
}
• If a class has no constructor in Java, the compiler will add a no-argument
constructor. A no-argument constructor is one that doesn’t have any
parameters, for example public Person().
• If a subclass has no call to a superclass constructor using super as the first line
in a subclass constructor then the compiler will automatically add
a super() call as the first line in a constructor. So, be sure to provide no-
argument constructors in parent classes or be sure to use an explicit call
to super() as the first line in the constructors of subclasses.
• Regardless of whether the superclass constructor is called implicitly or
explicitly, the process of calling superclass constructors continues until the
Object constructor is called since every class inherits from the Object class.

➔Abstract Method in Java


A method which is declared as abstract and does not have implementation is known
as an abstract method.

Example of abstract method

abstract void printStatus(); //no method body and abstract

➔Abstract class in Java


A class which is declared with the abstract keyword is known as an abstract class
in Java. It can have abstract and non-abstract methods (method with the body).

If a class contains an abstract method, then the class should be declared abstract.
Otherwise, it will generate an error.

o An abstract class must be declared with an abstract keyword.


o It can have abstract and non-abstract methods.
o It cannot be instantiated.
o It can have constructors and static methods also.
o It can have final methods which will force the subclass not to change the body
of the method.
o Though abstract classes cannot be instantiated, we can create subclasses from
it. We can then access members of the abstract class using the object of the
subclass.

abstract class Bank


{
abstract int getRateOfInterest();
}
class SBI extends Bank
{
int getRateOfInterest()
{
return 7;
}
}
class PNB extends Bank
{
int getRateOfInterest()
{
return 8;
}
}

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

▪ A class can extend only one class at a time.


▪ A class can implement any number of interfaces at a time.
▪ A class can extend a class and can implement any number of interfaces
simultaneously.
▪ An interface can extend any number of interfaces at a time.

interface A
{
}
interface B
{
}
// Extending Multiple Interfaces
interface C extends A,B
{
}
// implementing Multiple Interfaces
class D implements A,B
{
}

default methods in Java Interfaces


To declare default methods inside interfaces, we use the default keyword. For
example,

interface Polygon
{
void getArea();
default void getSides()
{
System.out.println("I can get sides of a polygon.");
}
}

class Rectangle implements Polygon


{
public void getArea()
{
int length = 6;
int breadth = 5;
int area = length * breadth;
System.out.println("The area of the rectangle is " + area);
}
public void getSides() {
System.out.println("I have 4 sides.");
}
}

// implements the interface


class Square implements Polygon
{
public void getArea()
{
int length = 5;
int area = length * length;
System.out.println("The area of the square is " + area);
}
}
class Main {
public static void main(String[] args)
{
Rectangle r1 = new Rectangle();
r1.getArea();
r1.getSides();
Square s1 = new Square();
s1.getArea();
s1.getSides();
}
}
private and static Methods in Interface
The Java 8 also added another feature to include static methods inside an interface.

interface Polygon {
void staticMethod(){..}
}

// access static method


Polygon.staticMethod();

➔Multiple Interface Inheritance Rules


what happens when a class implements several interfaces that define
the same default methods.
public interface Alarm
{
default String turnAlarmOn()
{
return "Turning the alarm on.";
}
default String turnAlarmOff()
{
return "Turning the alarm off.";
}
}
public interface Vehicle
{
String getBrand();
String speedUp();
String slowDown();
default String turnAlarmOn()
{
return "Turning the vehicle alarm on.";
}
default String turnAlarmOff()
{
return "Turning the vehicle alarm off.";
}
}
Now, the Car class would implement both Vehicle and Alarm:

public class Car implements Vehicle, Alarm


{
// ...
}
In this case, the code simply won't compile, as there's a conflict caused by
multiple interface inheritance.

To solve this ambiguity:

1. we must explicitly provide an implementation for the methods:

public String turnAlarmOn()


{
// custom implementation
}
public String turnAlarmOff()
{
// custom implementation
}
2. We can also have our class use the default methods of one of the
interfaces.

public String turnAlarmOn()


{
return Vehicle.super.turnAlarmOn();
}
public String turnAlarmOff()
{
return Vehicle.super.turnAlarmOff();
}

Similarly, we can have the class use the default methods defined within
the Alarm interface:

public String turnAlarmOn()


{
return Alarm.super.turnAlarmOn();
}
public String turnAlarmOff()
{
return Alarm.super.turnAlarmOff();
}
3. It's even possible to make the Car class use both sets of default
methods:

public String turnAlarmOn()


{
return Vehicle.super.turnAlarmOn() + " " + Alarm.super.turnAlarmOn();
}
public String turnAlarmOff()
{
return Vehicle.super.turnAlarmOff() + " " + Alarm.super.turnAlarmOff();
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy