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

Unit 2 Part 1 Java

Inheritance allows one class to acquire properties (methods and fields) of another class. The class that inherits is called a subclass, and the class that is inherited from is called a superclass. This allows code reuse so subclasses only need to define unique functionality. The main advantage is subclasses can use existing code from the superclass without rewriting it. Java uses the "extends" keyword for a subclass to inherit from a superclass. Types of inheritance in Java include single, multilevel, and hierarchical inheritance. Subclass constructors can call superclass constructors using the "super" keyword. Visibility modifiers like private, public, protected and default control access to classes, methods and fields.

Uploaded by

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

Unit 2 Part 1 Java

Inheritance allows one class to acquire properties (methods and fields) of another class. The class that inherits is called a subclass, and the class that is inherited from is called a superclass. This allows code reuse so subclasses only need to define unique functionality. The main advantage is subclasses can use existing code from the superclass without rewriting it. Java uses the "extends" keyword for a subclass to inherit from a superclass. Types of inheritance in Java include single, multilevel, and hierarchical inheritance. Subclass constructors can call superclass constructors using the "super" keyword. Visibility modifiers like private, public, protected and default control access to classes, methods and fields.

Uploaded by

DuRvEsH RaYsInG
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

Inheritance:

An important concept in object-oriented programming is inheritance. Inheritance can be


defined as the process where one class acquires the properties (methods and fields) of another.

The aim of inheritance is to provide the reusability of code so that a class has to write only the
unique features and rest of the common properties and functionalities can be extended from the
another class.

The biggest advantage of Inheritance is that the code that is already present in base class need
not be rewritten in the child class. This means that the data members(instance variables) and
methods of the parent class can be used in the child class too.

extends is the keyword used to inherit the properties of a class.

Java inheritance refers to the ability in Java for one class to inherit from another class. In Java
this is also called extending a class. One class can extend another class and thereby inherit from
that class.

When one class inherits from another class in Java, the two classes take on certain roles. The
class that extends (inherits from another class) is the subclass and the class that is being
extended (the class being inherited from) is the superclass . In other words, the subclass extends
the superclass. Or, the subclass inherits from the superclass.

• Superclass :

In the relationship between two objects, a superclass is the name given to the class that is being
inherited from. The class whose properties and functionalities are used(inherited) by another
class is known as parent class, super class or Base class.

To take a more real-world example this time, we could have a superclass called Person. Its state
holds the person's name, address, height, and weight, and has behaviours like go shopping,
make the bed, and watch TV.

We could make two new classes that inherit from Person called Student and Worker. They are
more specialized versions because although they have names, addresses, behaviours like watch
TV, and go shopping, they also have characteristics that are different from each other.

Worker could have a state that holds a job title and place of employment whereas Student might
hold data on an area of study and an institution of learning.
Superclass Example: Imagine you define a Person class:

public class Person

//Any code

A new class can be created by extending this class:

public class Employee extends Person

The Person class is said to be the superclass of the Employee class.

• Subclass :

In the relationship between two objects, a subclass is the name given to the class that is
inheriting from the superclass.

In the previous example, Student and Worker are the subclasses.

Subclasses can also be known as derived classes, child classes, or extended classes.

In Java, when a subclass inherits from a superclass, it's known as "extending" the superclass.

The class that extends the features of another class is known as child class, sub class or derived
class.

-------------------------------------------------------------------------------------------------------------

Defining Subclass :

The class that extends the features of another class is known as child class, sub class or derived
class. We can declare that a class is the subclass of another class within The Class Declaration.
For example, suppose that you wanted to create a subclass named SubClass of another class
named SuperClass. You would write:

class SubClass extends SuperClass {

...
}

This declares that SubClass is the subclass of the Superclass class. It also implicitly declares
that SuperClass is the superclass of SubClass. A subclass also inherits variables and methods
from its superclass's superclass, and so on up the inheritance tree.

A Java class can have only one direct superclass. Java does not support multiple inheritance.

Creating a subclass can be as simple as including the extends clause in your class declaration.

What Member Variables Does a Subclass Inherit?


• Subclasses inherit those member variables declared as public or protected.
• Subclasses inherit those member variables declared with no access specifier as long as the
subclass is in the same package as the superclass.
• Subclasses don't inherit a superclass's member variable if the subclass declares a member
variable using the same name. The subclass's member variable is said to hide the member
variable in the superclass.
• Subclasses don't inherit the superclass's private member variables.

What Methods Does a Subclass Inherit?

• Subclasses inherit those methods declared as public or protected.


• Subclasses inherit those superclass methods declared with no access specifier as long as
the subclass is in the same package as the superclass.
• Subclasses don't inherit a superclass's method if the subclass declares a method using the
same name. The method in the subclass is said to override the one in the superclass.
• Subclasses don't inherit the superclass's private methods.

Program Example :

public class Animal {

public static void eat() {

System.out.println("The eat method in Animal.");

} }

public class Cat extends Animal {

public static void eat() {


System.out.println("The eat method in Cat.");

public static void main(String[] args) {

Cat obj = new Cat();

obj.eat();

o/p :

The eat method in cat.

---------------------------------------------------------------------------------------------------------------

Types of Inheritance :

Inheritance can be defined as the process where one class acquires the properties (methods
and fields) of another. With the use of inheritance, the information is made manageable in a
hierarchical order.

The class which inherits the properties of other is known as subclass (derived class, child
class) and the class whose properties are inherited is known as superclass (base class, parent
class). extends is the keyword used to inherit the properties of a class.

1. Single Inheritance: In single inheritance, subclasses inherit the features of one superclass.
In image below, the class A serves as a base class for the derived class B.
Program Example :

2. Multilevel Inheritance: In Multilevel Inheritance, a derived class will be inheriting a base


class and as well as the derived class also act as the base class to other class. In below
image, the class A serves as a base class for the derived class B, which in turn serves as a
base class for the derived class C. In Java, a class cannot directly access the grandparent’s
members.
Program Example :
3. Hierarchical Inheritance: In Hierarchical Inheritance, one class serves as a superclass
(base class) for more than one sub class. In below image, the class A serves as a base
class for the derived class B, C and D.

Program Example :

----------------------------------------------------------------------------------------------------------------
Subclass Constructor:

• When we make any object of a subclass, 'super' is used to initialize its superclass first.
One more thing to note here is that 'super' must be called before any statements.
• super() calls the class's superclass constructor.
• If your method overrides one of its superclass's methods, you can invoke the overridden
method through the use of the keyword super.
• In Java, constructor of base class with no argument gets automatically called in derived
class constructor. For Example,

But, if we want to call parameterized constructor of base class, then we can call it using
super() (Super keyword). The point to note is base class constructor call must be the first line
in derived class constructor. For example, in the following program, super(5) is first line in
derived class constructor.
Visibility Control:

Java provides four types of visibility modifiers: default, public, private and protected. As the
name suggests access modifiers in Java helps to restrict the scope of a class, constructor,
variable, method or data member.

1) Default:

• When no access modifier is specified for a class, method or data member – It is said to be
having the default access modifier by default.

• The data members, class or methods which are not declared using any access modifiers i.e.
having default access modifier are accessible only within the same package.

• Default access modifier means we do not explicitly declare an access modifier for a class,
field, method, etc.

• A variable or method declared without any access control modifier is available to any other
class in the same package. The fields in an interface are implicitly public static final and the
methods in an interface are by default public.

Example :

Variables and methods can be declared without any modifiers, as in the following examples −
String str = "Hello";
boolean processOrder() {
return true;
}

2) Private:
• Methods, variables, and constructors that are declared private can only be accessed
within the declared class itself.
• Private access modifier is the most restrictive access level. Class and interfaces cannot
be private.
• Variables that are declared private can be accessed outside the class, if public getter
methods are present in the class.
• Using the private modifier is the main way that an object encapsulates itself and hides
data from the outside world.
Example :
The following class uses private access control −
public class Logger {
private String format;
public String getFormat() {
return this.format;
}
public void setFormat(String format) {
this.format = format;
}
}

Here, the format variable of the Logger class is private, so there's no way for other classes
to retrieve or set its value directly.
So, to make this variable available to the outside world, we defined two public methods:
getFormat(), which returns the value of format, and setFormat(String), which sets its
value.
3) Public
• A class, method, constructor, interface, etc. declared public can be accessed from any
other class. Therefore, fields, methods, blocks declared inside a public class can be
accessed from any class belonging to the Java Universe.
• However, if the public class we are trying to access is in a different package, then the
public class still needs to be imported. Because of class inheritance, all public methods
and variables of a class are inherited by its subclasses.

Example :
The following function uses public access control −
public static void main(String[] arguments) {
// ...
}
The main() method of an application has to be public. Otherwise, it could not be called by
a Java interpreter (such as java) to run the class.

4) Protected :
• Variables, methods, and constructors, which are declared protected in a superclass can
be accessed only by the subclasses in other package or any class within the package of the
protected members' class.
• The protected access modifier cannot be applied to class and interfaces. Methods, fields
can be declared protected, however methods and fields in a interface cannot be declared
protected.
• Protected access gives the subclass a chance to use the helper method or variable, while
preventing a nonrelated class from trying to use it.
Example
The following parent class uses protected access control, to allow its child class override
read() method −

class Demo {
protected boolean read() {
// implementation details
}
}
class Student extends Demo {
boolean read() {
// implementation details
}
}

Here, if we define read() method as private, then it would not be accessible from any other
class other than Demo. If we define it as public, then it would become accessible to all the
outside world. But our intention is to expose this method to its subclass only, that’s why we
have used protected modifier.

----------------------------------------------------------------------------------------------------------------

Method Overriding :

• In any object-oriented programming language, Overriding is a feature that allows a


subclass or child class to provide a specific implementation of a method that is already
provided by one of its super-classes or parent classes.
• When a method in a subclass has the same name, same parameters or signature and same
return type(or sub-type) as a method in its super-class, then the method in the subclass
is said to override the method in the super-class.
• Declaring a method in sub class which is already present in parent class is known as
method overriding.
• Overriding is done so that a child class can give its own implementation to a method
which is already provided by the parent class.
• In this case the method in parent class is called overridden method and the method in
child class is called overriding method.

Rules of method overriding in Java :

1) Argument list: The argument list of overriding method (method of child class) must
match the Overridden method(the method of parent class). The data types of the arguments and
their sequence should exactly match.

2) Access Modifier: Access Modifier of the overriding method (method of subclass)


cannot be more restrictive than the overridden method of parent class. For e.g. if the Access
Modifier of parent class method is public then the overriding method (child class method )
cannot have private, protected and default Access modifier,because all of these three access
modifiers are more restrictive than public.

Example :

Lets take a simple example to understand this. We have two classes: A child class Boy and a
parent class Human. The Boy class extends Human class. Both the classes have a common
method void eat(). Boy class is giving its own implementation to the eat() method or in other
words it is overriding the eat() method.

The purpose of Method Overriding is clear here. Child class wants to give its own
implementation so that when it calls this method, it prints Boy is eating instead of Human is
eating.

Advantage of method overriding:

The main advantage of method overriding is that the class can give its own specific
implementation to an inherited method without even modifying the parent class code.

This is helpful when a class has several child classes, so if a child class needs to use the parent
class method, it can use it and the other classes that want to have different implementation can
use overriding feature to make changes without touching the parent class code.

----------------------------------------------------------------------------------------------------------------
Dynamic Method Dispatch:

• Dynamic method dispatch is a technique by which call to a overridden method is resolved


at runtime, rather than compile time. When an overridden method is called by a reference,
then which version of overridden method is to be called is decided at runtime according
to the type of object it refers. Dynamic method dispatch is performed by JVM not
compiler.
• Dynamic method dispatch allows java to support overriding of methods and perform
runtime polymorphism. It allows subclasses to have common methods and can redefine
specific implementation for them. This lets the superclass reference respond differently
to same method call depending on which object it is pointing.
• When parent class reference variable refers to a child class object then its called upcasting
and using this technique dynamic method dispatch perform.

Program Example :
Super Keyword:

• The super keyword refers to the objects of immediate parent class.


• The super keyword in java is a reference variable that is used to refer parent class objects.
The keyword “super” came into the picture with the concept of Inheritance.
• The super keyword in Java is used in subclasses to access superclass members (attributes,
constructors and methods).
• It is used inside a sub-class method definition to call a method defined in the super class.
Private methods of the super-class cannot be called. Only public and protected methods
can be called by the super keyword.
• Super keyword are not used in static Method.

Uses of super keyword

1. To call methods of the superclass that is overridden in the subclass.


2. To access attributes (fields) of the superclass if both superclass and subclass have attributes
with the same name.
3. To explicitly call superclass no-arg (default) or parameterized constructor from the subclass
constructor.

1) super keyword to access the variables of parent class

When you have a variable in child class which is already present in the parent class then in
order to access the variable of parent class, you need to use the super keyword.
2. Use of super with methods: This is used when we want to call parent class method. So
whenever a parent and child class have same named methods then to resolve ambiguity we use
super keyword. This code snippet helps to understand the said usage of super keyword.

----------------------------------------------------------------------------------------------------------------
Abstract class and methods :

Abstraction is a process of hiding the implementation details and showing only functionality
to the user. Another way, it shows only essential things to the user and hides the internal
details, for example, sending SMS where you type the text and send the message. You don't
know the internal processing about the message delivery.

Abstraction lets you focus on what the object does instead of how it does it.

Ways to achieve Abstraction :

There are two ways to achieve abstraction in java

Abstract class (0 to 100%)

Interface (100%)

• Abstract class in Java :

A class which contains the abstract keyword in its declaration is known as abstract class.

Abstract classes may or may not contain abstract methods, i.e., methods without body.

But, if a class has at least one abstract method, then the class must be declared abstract.

If a class is declared abstract, it cannot be instantiated.

To use an abstract class, you have to inherit it from another class, provide implementations to
the abstract methods in it.

If you inherit an abstract class, you have to provide implementations to all the abstract
methods in it.

Program Example :

In this example, Shape is the abstract class, and its implementation is provided by the
Rectangle class.
• Abstract Methods :

A method without body (no implementation) is known as abstract method. A method must
always be declared in an abstract class, or in other words you can say that if a class has an
abstract method, it should be declared abstract as well.

Rules of Abstract Method

1. Abstract methods don’t have body, they just have method signature as shown above.

2. If a class has an abstract method it should be declared abstract, the vice versa is not true,
which means an abstract class doesn’t need to have an abstract method compulsory.

3. If a regular class extends an abstract class, then the class must have to implement all the
abstract methods of abstract parent class or it has to be declared abstract as well.

You might also like