0% found this document useful (0 votes)
5 views14 pages

Java lec 5

Inheritance in Java allows one class to inherit features from another, with subclasses inheriting properties and methods from superclasses. There are five types of inheritance: single, multilevel, multiple (via interfaces), hierarchical, and hybrid. The document also covers method overriding, the use of the super keyword, the final keyword, abstract classes, interfaces, and packages, detailing their definitions and functionalities.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views14 pages

Java lec 5

Inheritance in Java allows one class to inherit features from another, with subclasses inheriting properties and methods from superclasses. There are five types of inheritance: single, multilevel, multiple (via interfaces), hierarchical, and hybrid. The document also covers method overriding, the use of the super keyword, the final keyword, abstract classes, interfaces, and packages, detailing their definitions and functionalities.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 14

Inheritance

 Inheritance is the mechanism in Java by which one class can inherit the
features from another class.
 A class that inherits the features of another is known as child class/
subclass/ derived class and the class which is being inherited is known as
superclass/ parent class/ base class.
 A subclass inherits all the properties and methods of the super class, and
can have additional attributes and methods.

Types of Inheritance
 There are five different types of inheritance:
1) Single inheritance
2) Multilevel inheritance
3) Multiple inheritance
4) Hierarchical inheritance
5) Hybrid inheritance

1. Single inheritance:

 When sub-class is derived from only one super class, it is known as


a single inheritance.

2. Multilevel inheritance:
 When there is a chain of inheritance, it is known as multilevel
inheritance.
 In the below figure, 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.

3. Multiple inheritance:

 In multiple inheritance, one class can have more than one superclass
 Java does not support multiple inheritances with classes. In Java,
multiple inheritances can be achieved only through Interfaces.

4. Hierarchical inheritance:

 In Hierarchical Inheritance, one class serves as a superclass (base class)


for more than one subclass. In the below figure, class A serves as a base
class for the derived classes B, C, and D.
5. Hybrid inheritance:

 Hybrid inheritance is any combination of the above defined inheritances


as shown in below figure.

Deriving Classes Using extends Keyword:


 The extends keyword is used for inheritance.
 It allows a class to inherit the properties and methods of another class
(superclass or parent class).
Syntax:

class MySubClass extends MySuperClass


{
//methods and fields
}

In the above, the keyword extends declares that MySubClass inherits


the parent class MySuperClass.

Overriding Method

 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, when a method in a subclass has the same name, the
same parameters or signature, and the same return type as a method in
its super-class, then the method in the subclass is said to override the
method in the super-class.
 When an overridden method is called from within a subclass, it will
always refer to the version of the method defined by the subclass. The
superclass version of the method is hidden.
 A superclass reference variable can be assigned a subclass object. This is
illustrated by the following code:

package First_Package;
class super_class {
int i = 0;
void doOverride (int k) {
i = k;
}
}
class sub_class extends super_class {
void doOverride(int k)
{
i = 2 * k;
System.out.println("The value of i is: " +i);
}
}
public class new_class {
public static void main(String[] args) {

/* Create an instance of class sub_class but uses reference of super_class . */


sub_class sc = new sub_class();
sc.doOverride(12);

}
}

super Keyword:

 The super keyword is used to refer to the parent class.


 It is used for the following three purposes:
1) For accessing the member variables of the superclass.
2) For calling the methods of the superclass.
3) For invoking the constructors of the superclass.

Case 1: Accessing the Instance Member Variables of the Superclass


 If parent class and child class have same variable, then the variable of
the superclass is shadowed by the subclass variable.
 The superclass variable will be hidden and only subclass variables will be
accessible.
 To access the shadowed variable of superclass, super keyword is used
as shown below.

package First_Package;

class super_class
{
int b = 30;
}

public class sub_class extends super_class{


int b = 12;
void show()
{
System.out.println("subclass class variable:" + b);
System.out.println("superclass instance variable:" + super.b);
}

public static void main(String[] args) {


sub_classsc= new sub_class();
sc.show();
}
}

Case 2: Calling the Methods of the Superclass:


 When subclass contains the same method as parent class, you can use
super keyword to call the parent class's version of the method.
 super.<methodName>()represents a call to a method of the superclass.

package First_Package;

class super_class
{
void show()
{
System.out.println("superclass class method");
}
}

public class sub_class extends super_class{

void show()
{
super.show();
System.out.println("subclass class method");
}

public static void main(String[] args) {


sub_class sc = new sub_class();
sc.show();
}
}
Case 3: Invoking the Constructors of the Superclass:
 The super() keyword can also be used to call a constructor in the parent
class constructor.
 This call can be made only from the constructor of the subclass and that
too it should be the first statement of the constructors.
 The default constructors implicitly include a call to the super class
constructor using the super keyword.

Example:
package First_Package;
class super_class2
{
super_class2(String name)
{
System.out.println("Super Class Constructor : " + name );
}
}

public class sub_class2 extends super_class2{

sub_class2(String name)
{
super(name);
System.out.println("Sub Class Constructor : " + name );
}

public static void main(String[] args)


{
sub_class2 sc = new sub_class2("Hello");
}
}

final Keyword:

 The keyword final is used for the following purposes:


1. To declare constants (used with variable and argument declaration)
2. To disallow method overriding (used with method declaration)
3. To disallow inheritance (used with class declaration)
 Basically, it is used to prevent inheritance and create constants.

Example:

package First_Package;

class super_class
{
final int MAX = 100;
final void show(final int x)
{
// MAX++; illegal statement as MAX is final
// x++; illegal statement as x argument is final
System.out.println("Superclass show method: " +x);
}
}
public class sub_class extends super_class {

//cannot override show method as it is final in parent class

/*void show(int x){


System.out.println("Subclass show method: " + x);
}*/
public static void main(String[] args) {
sub_class sc = new sub_class();
sc.show(12);
}

Abstract Class:

 A class that is declared with the abstract keyword is known as an


abstract class in Java.
 It can have abstract methods as well as non-abstract methods(method
with the body).
 An abstract method is a method that contains no implementation, i.e.,
no body.
 Implementation of an abstract method can be provided by subclass, if
the subclasses do not implement the methods of the abstract class, then
it is mandatory for the subclasses to tag itself as abstract.
 The abstract keyword is used for defining both abstract methods and
abstract classes.
 Abstract classes cannot be instantiated, and they require subclasses to
provide implementation for their abstract methods by overriding them
and then the subclasses can be instantiated.

Why do We Create Abstract Methods?


 We use abstract methods, when we want to force the same name and
signature pattern in all the subclasses and do not want to give them the
opportunity to use their own naming patterns, but at the same time give
them the flexibility to code these methods with their own specific
requirements.

Key features of an abstract class are as follows:


1. An abstract class must be declared with an abstract keyword.
2. It cannot be instantiated.
3. It can have abstract methods as well as non-abstract methods.
4. It is mandatory for a subclass to override the abstract methods of the
abstract class, otherwise the subclass also need to declare itself as
abstract.
5. Abstract classes can have constructors and variables, just like other
normal classes.

// Abstract class
abstract class Animal {
// Abstract method
abstract void sound();

// Non-abstract method
void eat() {
System.out.println("The animal eats.");
}
}

// Concrete subclass
class Dog extends Animal {
// Implement the abstract method
void sound() {
System.out.println("The dog barks.");
}
}

public class Main {


public static void main(String[] args) {
Dog myDog = new Dog();
myDog.sound(); // Outputs: The dog barks.
myDog.eat(); // Outputs: The animal eats.
}
}

Interface & Packages:

Interfaces

 Interfaces are basically a collection of methods which are public and


abstract by default. These methods do not have any body.
 The implementing classes have to override all the methods of the
interface and provide implementation for all these methods.
 Java does not support multiple inheritance among classes, but this
feature can be achieved using interfaces.
 Interfaces are declared using keyword interface.
 We do not want the classes to follow their own set of rules like their
own method names and their own signature patterns. We wanted the
classes to follow the rules defined by the interfaces and do not want to
give them an opportunity to use their own naming patterns, but at the
same time give them the flexibility to code these methods with their
own specific requirements.

Variables in Interface:

 Variables defined in an interface are implicitly public, final, and static


and there is no need to explicitly declare them as public, static, and final.
o As they are final, they need to be assigned a value compulsorily.
o Being static, they can be accessed directly with the help of an
interface name.
o as they are public, we can access them from anywhere.
Extending Interfaces:
 Just like normal classes, interfaces can also be extended.
 An interface can inherit another interface using the same keyword
extends, and not the keyword implements.

Interface vs Abstract Classes

Key point Interface Abstract Class

Keyword implements keyword is used to extends keyword is used to inherit


inherit an interface. a class.
Multiple Multiple inheritance is possible; a Multiple inheritance is not
Inheritance class can inherit multiple possible; a class can inherit only
interfaces. one class.
Constructors Interfaces do not have any Abstract classes can have
constructors. constructors.
Methods All methods are abstract by Can have a mix of abstract and
default. non- abstract methods.
Implementation Interfaces have no implementation Abstract classes can have partial
at all. implementation.
Method All methods of an interface need to Only abstract methods need to be
Overriding be overridden. overridden.
Requirement
Fields/Variables All variables in interface are by variables are not by default public,
default public, static, and final. static, or final; you must explicitly
specify public, static, or final if
required.
Access Methods are implicitly public and Methods have to be tagged as
Modifiers for abstract. public or abstract, if required.
Methods

Packages
 Package in java is a group of similar types of classes, interfaces and sub-
packages.

 Java packages can be categorized into two types:


o Built-in Packages – Provided by Java.
o User-defined Packages – Created by developers to organize code
efficiently.

1. Built-in Packages
 These packages consist of a large number of classes which are a part of
Java.Some of the commonly used built-in packages are:

2. User-defined Packages
 These are the packages that are defined by the user.

Advantages of using package:


1. Avoids Name Conflicts
2. Better Code Organization & Structure
3. Code Reusability
4. Controlled Access with Access Modifiers
5. Reduces Complexity & Improves Maintainability

1. Avoids Name Conflicts:


 Packages allow developers to have same class name in different
packages.
 Example: You can have college.staff.cse.Employee and
college.staff.ee.Employee.

2. Code Reusability
 Once a package is created, it can be reused in multiple projects.
 Encourages modular programming by grouping related classes together.

3. Better Code Organization & Structure


 Helps in structuring large applications by dividing code into related
groups.

4. Controlled Access with Access Modifiers


 Packages provide security by restricting access to classes using private,
protected, and public access modifiers.

5. Reduces Complexity & Improves Maintainability


 Developers can focus on specific packages instead of dealing with the
entire project.

Creating Packages
 To create a package, use the package keyword at the beginning of a Java
file.

package mypackage; // Declaring package

public class MyClass {


public void display() {
System.out.println("Hello from MyClass in mypackage!");
}
}

Using Packages

 In Java, you can import classes from a package using either of the
following methods:
1. Import a specific class:
import mypackage.MyClass;

2. Import all classes from a package:


import mypackage.*;

Access Protection

 Access modifiers in Java specifies the accessibility or scope of a field,


method, constructor, or class.
 There are four types of Java access modifiers:

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