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

Module_2 (4)

The document provides an overview of Java inheritance, detailing its types such as single, multilevel, hierarchical, multiple, and hybrid inheritance. It explains key concepts like method overriding, access specifiers, and the use of the 'super' keyword, along with rules governing inheritance in Java. Additionally, it emphasizes the is-a relationship in inheritance and outlines examples to illustrate these concepts.

Uploaded by

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

Module_2 (4)

The document provides an overview of Java inheritance, detailing its types such as single, multilevel, hierarchical, multiple, and hybrid inheritance. It explains key concepts like method overriding, access specifiers, and the use of the 'super' keyword, along with rules governing inheritance in Java. Additionally, it emphasizes the is-a relationship in inheritance and outlines examples to illustrate these concepts.

Uploaded by

Jayadeep Royal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 101

Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance

ce protected

Object Oriented
Programming
Module 2: Inheritance

Dr. Nikhil Mhala

[email protected]
School of Computer Science and Engineering (SCOPE)
VIT-AP University (Besides AP Secretariat) 522237

May 8, 2022

Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 1 / 101


Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance protected

Agenda I

protected Members in Inheri-


6
1 Java Inheritance tance
2 Types of inheritance 7 Why use inheritance?
8 Abstract Class and Method
3 Java Method Overriding
9 Java Abstraction
4 Access Specifiers in Method 10 Java Interfaces
Overriding 11 Java Polymorphism
5 super Keyword in Java Inheri- 12 Java Encapsulation
tance 13 Java Nested and Inner Class

Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 2 / 101


Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance protected

Java Inheritance
Inheritance is one of the key features of OOP that allows us
to create a new class from an existing class.
The new class that is created is known as subclass (child or
derived class) and the existing class from where the child class
is derived is known as superclass (parent or base class).
The extends keyword is used to perform inheritance in Java
1 class Animal {
2 // methods and fields
3 }
4
5 // use of extends keyword
6 // to perform inheritance
7 class Dog extends Animal {
8
9 // methods and fields of Animal
10 // methods and fields of Dog
11 }
12

Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 3 / 101


Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance protected

Example : Java Inheritance

1 class Animal {
2
3 // field and method of the parent class
4 String name ;
5 public void eat () {
6 System . out . println ( " I can eat " ) ;
7 }
8 }
9
10 // inherit from Animal
11 class Dog extends Animal {
12
13 // new method in subclass
14 public void display () {
15 System . out . println ( " My name is " + name ) ;
16 }
17 }

./code/InheritanceExample.java

Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 4 / 101


Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance protected

Example : Java Inheritance

18 class Main {
19 public static void main ( String [] args ) {
20
21 // create an object of the subclass
22 Dog labrador = new Dog () ;
23
24 // access field of superclass
25 labrador . name = " Jerry " ;
26 labrador . display () ;
27
28 // call method of superclass
29 // using object of subclass
30 labrador . eat () ;
31
32 }
33 }

./code/InheritanceExample.java

Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 5 / 101


Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance protected

Java Inheritance Implementation

Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 6 / 101


Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance protected

is-a relationship

In Java, inheritance is an is-a relationship. That is, we use inheri-


tance only if there exists an is-a relationship between two classes
Car is a Vehicle
Orange is a Fruit
Surgeon is a Doctor
Dog is an Animal
Here, Car can inherit from Vehicle, Orange can inherit from Fruit, and
so on.

Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 7 / 101


Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance protected

Types of Inheritance

1 Single Inheritance
2 Multilevel Inheritance
3 Hierarchical Inheritance
4 Multiple Inheritance
5 Hybrid Inheritance

Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 8 / 101


Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance protected

1. Single Inheritance

In single inheritance, a single subclass extends from a single


superclass

Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 9 / 101


Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance protected

1. Single Inheritance

1 class Animal {
2 void eat () { System . out . println ( " eating " ) ;}
3 }
4 class Dog extends Animal {
5 void bark () { System . out . println ( " barking " ) ;}
6 }
7 class Te st I nh e ri ta n ce {
8 public static void main ( String args []) {
9 Dog d = new Dog () ;
10 d . bark () ;
11 d . eat () ;
12 }
13 }

./code/SingelLevelInheritance.java

Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 10 / 101


Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance protected

2. Multilevel Inheritance
In multilevel inheritance, a subclass extends from a superclass
and then the same subclass acts as a superclass for another
class.

Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 11 / 101


Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance protected

2. Multilevel Inheritance

1 class Animal {
2 void eat () { System . out . println ( " eating " ) ;}
3 }
4 class Dog extends Animal {
5 void bark () { System . out . println ( " barking " ) ;}
6 }
7 class Puppy extends Dog {
8 void weep () { System . out . println ( " weeping " ) ;}
9 }
10 class T e s t I n h e r i t a n c e 2 {
11 public static void main ( String args []) {
12 Puppy d = new Puppy () ;
13 d . weep () ;
14 d . bark () ;
15 d . eat () ;
16 }
17 }

./code/MultiLevelInheritance.java

Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 12 / 101


Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance protected

3. Hierarchical Inheritance

In hierarchical inheritance, multiple subclasses extend from a


single superclass

Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 13 / 101


Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance protected

3. Hierarchical Inheritance

1 class Animal {
2 void eat () { System . out . println ( " eating " ) ;}
3 }
4 class Dog extends Animal {
5 void bark () { System . out . println ( " barking " ) ;}
6 }
7 class Cat extends Animal {
8 void meow () { System . out . println ( " meowing " ) ;}
9 }
10 class T e s t I n h e r i t a n c e 3 {
11 public static void main ( String args []) {
12 Cat c = new Cat () ;
13 c . meow () ;
14 c . eat () ;
15 }
16 }

./code/HierarchicalInheritance.java

Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 14 / 101


Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance protected

4. Multiple Inheritance
In multiple inheritance, a single subclass extends from multiple
superclasses.

Note: Java doesn’t support multiple inheritance. However, we


can achieve multiple inheritance using interfaces
Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 15 / 101
Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance protected

5. Hybrid Inheritance

Hybrid inheritance is a combination of two or more types of


inheritance

Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 16 / 101


Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance protected

Rules of Inheritance
RULE 1: Multiple Inheritance is NOT permitted in Java.
1 class Demo1
2 {
3 // code here }
4 class Demo2
5 {
6 // code here }
7 class Demo3 extends Demo1 , Demo2
8 {
9 // code here }
10 class Launch
11 {
12 public static void main ( String args [])
13 {
14 // code here
15 } }

This is not permitted as it results in a diamond problem and leads to


ambiguity.
Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 17 / 101
Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance protected

Rules of Inheritance

RULE 2: Cyclic Inheritance is NOT permitted in Java.


1 class Demo1 extends Demo2
2 {
3 // code here
4 }
5 class Demo2 extends Demo1
6 {
7 // code here
8 }

In the above code, both the classes are trying to inherit each other’s
characters which is not permitted as it leads to ambiguity.

Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 18 / 101


Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance protected

Rules of Inheritance

RULE 3: Private members do NOT get inherited.


1 class You
2 {
3 private int an ;
4 private int pw ;
5 You () {
6 an =111;
7 pw = 222;
8 }
9 }

./code/PrivateInheritance.java

Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 19 / 101


Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance protected

Rules of Inheritance

RULE 3: Private members do NOT get inherited.


10 class Friend extends You
11 {
12 void changeData ()
13 {
14 an =8888;
15 pw =9999;
16 }
17 void disp ()
18 {
19 System . out . println ( an ) ;
20 System . out . println ( pw ) ;
21 }
22 }

./code/PrivateInheritance.java

Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 20 / 101


Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance protected

Rules of Inheritance

RULE 3: Private members do NOT get inherited.


24 class Launch
25 {
26 public static void main ( String args [])
27 {
28 Friend f = new Friend () ;
29 f . changeData () ;
30 f . disp () ;
31 }
32 }

./code/PrivateInheritance.java

When you execute the above code, guess what happens, do you
think the private variables an and pw will be inherited? Absolutely not.
It remains the same because they are specific to the particular class

Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 21 / 101


Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance protected

Rules of Inheritance

RULE 4: Constructors cannot be Inherited in Java.


1 class A {
2 A () ;}
3
4 class B extends A {
5 B () ;}
6 \\ You can do only :
7 B b = new B () ; // and not new A ()

Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 22 / 101


Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance protected

Java Method Overriding

Inheritance is an OOP property that allows us to derive a new


class (subclass) from an existing class (superclass). The
subclass inherits the attributes and methods of the superclass.
Now, if the same method is defined in both the superclass and
the subclass, then the method of the subclass class overrides
the method of the superclass. This is known as method
overriding.

Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 23 / 101


Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance protected

Example : Method Overriding

1 class Animal {
2 public void displayInfo () {
3 System . out . println ( " I am an animal . " ) ;
4 }
5 }
6 class Dog extends Animal {
7 // @Override
8 public void displayInfo () {
9 System . out . println ( " I am a dog . " ) ;
10 }
11 }
12
13 class Main {
14 public static void main ( String [] args ) {
15 Dog d1 = new Dog () ;
16 d1 . displayInfo () ;
17 }
18 }

./code/MethodOverriding.java

Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 24 / 101


Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance protected

Java Overriding Rules

Both the superclass and the subclass must have the same
method name, the same return type and the same parameter
list.
We cannot override the method declared as final and static.
We should always override abstract methods of the superclass

Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 25 / 101


Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance protected

Access Specifiers in Method Overriding

The same method declared in the superclass and its subclasses


can have different access specifiers. However, there is a
restriction.
We can only use those access specifiers in subclasses that
provide larger access than the access specifier of the
superclass.
Example : Suppose, a method myClass() in the superclass is
declared protected. Then, the same method myClass() in the
subclass can be either public or protected, but not private

Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 26 / 101


Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance protected

Access Specifiers in Method Overriding

1 class Animal {
2 protected void displayInfo () {
3 System . out . println ( " I am an animal . " ) ;
4 }
5 }
6
7 class Dog extends Animal {
8 public void displayInfo () {
9 System . out . println ( " I am a dog . " ) ;
10 }
11 }
12
13 class Main {
14 public static void main ( String [] args ) {
15 Dog d1 = new Dog () ;
16 d1 . displayInfo () ;
17 }
18 }

./code/AccessSpecifierInOverriding.java

Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 27 / 101


Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance protected

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.

Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 28 / 101


Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance protected

super Keyword in Java Inheritance

we saw that the same method in the subclass overrides the


method in superclass.
In such a situation, the super keyword is used to call the method
of the parent class from the method of the child class.

Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 29 / 101


Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance protected

Example: super Keyword in Inheritance


1 class Animal {
2 // method in the superclass
3 public void eat () {
4 System . out . println ( " I can eat " ) ;
5 }
6 }
7 // Dog inherits Animal
8 class Dog extends Animal {
9 // overriding the eat () method
10 @Override
11 public void eat () {
12 // call method of superclass
13 super . eat () ;
14 System . out . println ( " I eat dog food " ) ;
15 }
16 // new method in subclass
17 public void bark () {
18 System . out . println ( " I can bark " ) ;
19 }
20 }

./code/SuperKeyword.java
Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 30 / 101
Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance protected

Example: super Keyword in Inheritance

21 class Main {
22 public static void main ( String [] args ) {
23
24 // create an object of the subclass
25 Dog labrador = new Dog () ;
26
27 // call the eat () method
28 labrador . eat () ;
29 labrador . bark () ;
30 }
31 }

./code/SuperKeyword.java

It is important to note that constructors in Java are not inherited.


Hence, there is no such thing as constructor overriding in Java.
However, we can call the constructor of the superclass from its sub-
classes. For that, we use super()

Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 31 / 101


Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance protected

Use of super() to access superclass con-


structor

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

Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 32 / 101


Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance protected

Example: Use of super()


1 class Animal {
2 // default or no - arg constructor of class Animal
3 Animal () {
4 System . out . println ( " I am an animal " ) ;
5 }
6 }
7 class Dog extends Animal {
8 // default or no - arg constructor of class Dog
9 Dog () {
10 // calling default constructor of the superclass
11 super () ;
12 System . out . println ( " I am a dog " ) ;
13 }
14 }
15 class Main {
16 public static void main ( String [] args ) {
17 Dog dog1 = new Dog () ;
18 }
19 }

./code/SuperConstructor.java

Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 33 / 101


Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance protected

protected Members in Inheritance

In Java, if a class includes protected fields and methods, then these


fields and methods are accessible from the subclass of the class.
1 class Animal {
2 protected String name ;
3
4 protected void display () {
5 System . out . println ( " I am an animal . " ) ;
6 }
7 }
8
9 class Dog extends Animal {
10
11 public void getInfo () {
12 System . out . println ( " My name is " + name ) ;
13 }
14 }

./code/ProtectedDemo.java

Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 34 / 101


Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance protected

Protected Members in Inheritance

15
16 class Main {
17 public static void main ( String [] args ) {
18
19 // create an object of the subclass
20 Dog labrador = new Dog () ;
21
22 // access protected field and method
23 // using the object of subclass
24 labrador . name = " Rocky " ;
25 labrador . display () ;
26
27 labrador . getInfo () ;
28 }
29 }

./code/ProtectedDemo.java

Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 35 / 101


Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance protected

Why use inheritance?

The most important use of inheritance in Java is code reusability.


The code that is present in the parent class can be directly used
by the child class.
Method overriding is also known as runtime polymorphism.
Hence, we can achieve Polymorphism in Java with the help of
inheritance.

Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 36 / 101


Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance protected

Java Abstract Class

The abstract class in Java cannot be instantiated (we cannot


create objects of abstract classes). We use the abstract keyword
to declare an abstract class.
1 // create an abstract class
2 abstract class Language {
3 // fields and methods
4 }
5 ...
6
7 // try to create an object Language
8 // throws an error
9 Language obj = new Language () ;

Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 37 / 101


Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance protected

Java Abstract Class

An abstract class can have both the regular methods and abstract
methods
1 abstract class Language {
2
3 // abstract method
4 abstract void method1 () ;
5
6 // regular method
7 void method2 () {
8 System . out . println ( " This is regular method " ) ;
9 }
10 }

Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 38 / 101


Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance protected

Java Abstract Method


A method that doesn’t have its body is known as an abstract
method. We use the same abstract keyword to create abstract
methods
1 abstract void display () ;

If a class contains an abstract method, then the class should be de-


clared abstract. Otherwise, it will generate an error
1 // error
2 // class should be abstract
3 class Language {
4
5 // abstract method
6 abstract void method1 () ;
7 }

Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 39 / 101


Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance protected

Example: Java Abstract Class and Method


Though abstract classes cannot be instantiated, we can create sub-
classes from it. We can then access members of the abstract class
using the object of the subclass.
1 abstract class Language {
2 // method of abstract class
3 public void display () {
4 System . out . println ( " This is Java Programming " ) ;
5 }
6 }
7 class Main extends Language {
8 public static void main ( String [] args ) {
9
10 // create an object of Main
11 Main obj = new Main () ;
12
13 // access method of abstract class
14 // using object of Main class
15 obj . display () ;
16 }
17 }

./code/AbstarctMethiod.java
Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 40 / 101
Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance protected

Implementing Abstract Methods


If the abstract class includes any abstract method, then all the
child classes inherited from the abstract superclass must pro-
vide the implementation of the abstract method.
1 abstract class Animal {
2 abstract void makeSound () ;
3 public void eat () {
4 System . out . println ( " I can eat . " ) ;
5 }
6 }
7 class Dog extends Animal {
8 // provide im plemen tation of abstract method
9 public void makeSound () {
10 System . out . println ( " Bark bark " ) ;} }
11 class Main {
12 public static void main ( String [] args ) {
13 // create an object of Dog class
14 Dog d1 = new Dog () ;
15 d1 . makeSound () ;
16 d1 . eat () ; } }

./code/AbstarctMethod.java

Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 41 / 101


Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance protected

Note: Abstract Method

Note: If the Dog class doesn’t provide the implementation of the ab-
stract method makeSound(), Dog should also be declared as ab-
stract. This is because the subclass Dog inherits makeSound() from
Animal.

Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 42 / 101


Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance protected

Accesses Constructor of Abstract Classes

An abstract class can have constructors like the regular class. And,
we can access the constructor of an abstract class from the subclass
using the super keyword.
1 abstract class Animal {
2 Animal () {
3 ...
4 }
5 }
6
7 class Dog extends Animal {
8 Dog () {
9 super () ;
10 ...
11 }
12 }

Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 43 / 101


Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance protected

Java Abstraction

The major use of abstract classes and methods is to achieve


abstraction in Java.
Abstraction is an important concept of object-oriented
programming that allows us to hide unnecessary details and only
show the needed information
This allows us to manage complexity by omitting or hiding details
with a simpler, higher-level idea

Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 44 / 101


Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance protected

Example; Java Abstraction


1 abstract class MotorBike {
2 abstract void brake () ;
3 }
4
5 class SportsBike extends MotorBike {
6
7 // implemen tation of abstract method
8 public void brake () {
9 System . out . println ( " SportsBike Brake " ) ;
10 }
11 }
12
13 class MountainBike extends MotorBike {
14
15 // implemen tation of abstract method
16 public void brake () {
17 System . out . println ( " MountainBike Brake " ) ;
18 }
19 }

./code/MotorBike.java

Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 45 / 101


Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance protected

Example; Java Abstraction

20
21 class Main {
22 public static void main ( String [] args ) {
23 MountainBike m1 = new MountainBike () ;
24 m1 . brake () ;
25 SportsBike s1 = new SportsBike () ;
26 s1 . brake () ;
27 }
28 }

./code/MotorBike.java

Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 46 / 101


Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance protected

Key Points to Remember

We use the abstract keyword to create abstract classes and


methods.
An abstract method doesn’t have any implementation (method
body).
A class containing abstract methods should also be abstract.
We cannot create objects of an abstract class.

Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 47 / 101


Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance protected

Key Points to Remember

To implement features of an abstract class, we inherit


subclasses from it and create objects of the subclass.
A subclass must override all abstract methods of an abstract
class. However, if the subclass is declared abstract, it’s not
mandatory to override abstract methods.
We can access the static attributes and methods of an abstract
class using the reference of the abstract class

Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 48 / 101


Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance protected

Key Points to Remember

To implement features of an abstract class, we inherit


subclasses from it and create objects of the subclass.
A subclass must override all abstract methods of an abstract
class. However, if the subclass is declared abstract, it’s not
mandatory to override abstract methods.
We can access the static attributes and methods of an abstract
class using the reference of the abstract class
1 Animal . staticMethod () ;

Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 49 / 101


Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance protected

Java Interface

An interface is a fully abstract class. It includes a group of


abstract methods (methods without a body).
We use the interface keyword to create an interface in Java.
Like abstract classes, we cannot create objects of interfaces
1 interface Language {
2 public void getType () ;
3
4 public void getVersion () ;
5 }

Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 50 / 101


Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance protected

Implementing an Interface
To use an interface, other classes must implement it. We use
the implements keyword to implement an interface
1 interface Polygon {
2 void getArea ( int length , int breadth ) ;
3 }
4 // implement the Polygon interface
5 class Rectangle implements Polygon {
6
7 // implemen tation of abstract method
8 public void getArea ( int length , int breadth ) {
9 System . out . println ( " The area of the rectangle is " + (
length * breadth ) ) ;
10 }
11 }
12 class Main {
13 public static void main ( String [] args ) {
14 Rectangle r1 = new Rectangle () ;
15 r1 . getArea (5 , 6) ;
16 }
17 }

./code/InterfaceExample.java
Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 51 / 101
Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance protected

Example: Java Interface


1 // create an interface
2 interface Language {
3 void getName ( String name ) ;
4 }
5
6 // class implements interface
7 class P r o g r a m m i n g L a n g u a g e implements Language {
8
9 // implemen tation of abstract method
10 public void getName ( String name ) {
11 System . out . println ( " Programming Language : " + name ) ;
12 }
13 }
14
15 class Main {
16 public static void main ( String [] args ) {
17 P r o g r a m m i n g L a n g u a g e language = new P r o g r a m m i n g L a n g u a g e ()
;
18 language . getName ( " Java " ) ;
19 }
20 }

./code/JavaInterfaceExample.java
Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 52 / 101
Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance protected

Implementing Multiple Interfaces

In Java, a class can also implement multiple interfaces. For example,


1 interface A {
2 // members of A
3 }
4
5 interface B {
6 // members of B
7 }
8
9 class C implements A , B {
10 // abstract members of A
11 // abstract members of B
12 }

Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 53 / 101


Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance protected

Extending an Interface

Similar to classes, interfaces can extend other interfaces. The


extends keyword is used for extending interfaces.
1 interface Line {
2 // members of Line interface
3 }
4
5 // extending interface
6 interface Polygon extends Line {
7 // members of Polygon interface
8 // members of Line interface
9 }

Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 54 / 101


Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance protected

Extending Multiple Interfaces

An interface can extend multiple interfaces.


1 interface A {
2 . . .
3 }
4 interface B {
5 . . .
6 }
7
8 interface C extends A , B {
9 . . .
10 }

Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 55 / 101


Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance protected

Advantages of Interface in Java

Similar to abstract classes, interfaces help us to achieve


abstraction in Java.
Here, we know getArea() calculates the area of polygons but the
way area is calculated is different for different polygons. Hence,
the implementation of getArea() is independent of one another
Interfaces provide specifications that a class (which
implements it) must follow.
In our previous example, we have used getArea() as a
specification inside the interface Polygon. This is like setting a
rule that we should be able to get the area of every polygon.
Now any class that implements the Polygon interface must
provide an implementation for the getArea() method

Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 56 / 101


Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance protected

Advantages of Interface in Java

Interfaces are also used to achieve multiple inheritance in Java.


1 interface Line {
2 . . .
3 }
4
5 interface Polygon {
6 . . .
7 }
8
9 class Rectangle implements Line , Polygon {
10 . . .
11 }

Here, the class Rectangle is implementing two different


interfaces. This is how we achieve multiple inheritance in Java.

Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 57 / 101


Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance protected

Note: Interfaces

All the methods inside an interface are implicitly public and all fields
are implicitly public static final
1 interface Language {
2
3 // by default public static final
4 String type = " programming language " ;
5
6 // by default public
7 void getName () ;
8 }

Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 58 / 101


Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance protected

default methods in Java Interfaces

We can add methods with implementation inside an interface. These


methods are called default methods.
To declare default methods inside interfaces, we use the default key-
word
1 public default void getSides () {
2 // body of getSides ()
3 }

Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 59 / 101


Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance protected

Why default methods?

Let’s take a scenario to understand why default methods are


introduced in Java
Suppose, we need to add a new method in an interface
We can add the method in our interface easily without
implementation. However, that’s not the end of the story. All our
classes that implement that interface must provide an
implementation for the method
If a large number of classes were implementing this interface, we
need to track all these classes and make changes to them. This
is not only tedious but error-prone as well.
To resolve this, Java introduced default methods. Default
methods are inherited like ordinary methods

Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 60 / 101


Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance protected

Example: Default Method in Java Interface


1 interface Polygon {
2 void getArea () ;
3 // default method
4 default void getSides () {
5 System . out . println ( " I can get sides of a polygon . " ) ;
6 }
7 }
8 // implements the interface
9 class Rectangle implements Polygon {
10 public void getArea () {
11 int length = 6;
12 int breadth = 5;
13 int area = length * breadth ;
14 System . out . println ( " The area of the rectangle is " +
area ) ;
15 }
16 // overrides the getSides ()
17 public void getSides () {
18 System . out . println ( " I have 4 sides . " ) ;
19 }
20 }

./code/DefaultMethodInInterface.java
Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 61 / 101
Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance protected

Example: Default Method in Java Interface


21 // implements the interface
22 class Square implements Polygon {
23 public void getArea () {
24 int length = 5;
25 int area = length * length ;
26 System . out . println ( " The area of the square is " + area ) ;
27 }
28 }
29 class Main {
30 public static void main ( String [] args ) {
31 // create an object of Rectangle
32 Rectangle r1 = new Rectangle () ;
33 r1 . getArea () ;
34 r1 . getSides () ;
35
36 // create an object of Square
37 Square s1 = new Square () ;
38 s1 . getArea () ;
39 s1 . getSides () ;
40 }
41 }

./code/DefaultMethodInInterface.java
Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 62 / 101
Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance protected

private and static Methods in Interface

The Java also added another feature to include static methods inside
an interface
Similar to a class, we can access static methods of an interface using
its references
1 // create an interface
2 interface Polygon {
3 staticMethod () {..}
4 }
5
6 // access static method
7 Polygon . staticMethod () ;

Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 63 / 101


Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance protected

Practical Example of Interface

1 // To use the sqrt function


2 import java . lang . Math ;
3
4 interface Polygon {
5 void getArea () ;
6
7 // calculate the perimeter of a Polygon
8 default void getPerimeter ( int ... sides ) {
9 int perimeter = 0;
10 for ( int side : sides ) {
11 perimeter += side ;
12 }
13
14 System . out . println ( " Perimeter : " + perimeter ) ;
15 }
16 }

./code/InterfacePracticalexample.java

Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 64 / 101


Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance protected

Practical Example of Interface


1 class Triangle implements Polygon {
2 private int a , b , c ;
3 private double s , area ;
4
5 // initializing sides of a triangle
6 Triangle ( int a , int b , int c ) {
7 this . a = a ;
8 this . b = b ;
9 this . c = c ;
10 s = 0;
11 }
12
13 // calculate the area of a triangle
14 public void getArea () {
15 s = ( double ) ( a + b + c ) /2;
16 area = Math . sqrt ( s *( s - a ) *( s - b ) *( s - c ) ) ;
17 System . out . println ( " Area : " + area ) ;
18 }
19 }

./code/InterfacePracticalexample.java

Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 65 / 101


Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance protected

Practical Example of Interface

1
2 class Main {
3 public static void main ( String [] args ) {
4 Triangle t1 = new Triangle (2 , 3 , 4) ;
5
6 // calls the method of the Triangle class
7 t1 . getArea () ;
8
9 // calls the method of Polygon
10 t1 . getPerimeter (2 , 3 , 4) ;
11 }
12 }

./code/InterfacePracticalexample.java

Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 66 / 101


Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance protected

Java Polymorphism

Polymorphism is an important concept of object-oriented pro-


gramming. It simply means more than one form.
That is, the same entity (method or operator or object) can perform
different operations in different scenarios.

Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 67 / 101


Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance protected

Example: Java Polymorphism


1 class Polygon {
2 // method to render a shape
3 public void render () {
4 System . out . println ( " Rendering Polygon ... " ) ;
5 }
6 }
7 class Square extends Polygon {
8
9 // renders Square
10 public void render () {
11 System . out . println ( " Rendering Square ... " ) ;
12 }
13 }
14 class Circle extends Polygon {
15 // renders circle
16 public void render () {
17 System . out . println ( " Rendering Circle ... " ) ;
18 }
19 }

./code/JavaPolymorphism.java

Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 68 / 101


Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance protected

Example: Java Polymorphism

21 class Main {
22 public static void main ( String [] args ) {
23
24 // create an object of Square
25 Square s1 = new Square () ;
26 s1 . render () ;
27
28 // create an object of Circle
29 Circle c1 = new Circle () ;
30 c1 . render () ;
31 }
32 }

./code/JavaPolymorphism.java

Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 69 / 101


Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance protected

Types of Techniques to achieve Polymor-


phism

We can achieve polymorphism in Java using the following ways:


1 Method Overriding
2 Method Overloading
3 Operator Overloading

Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 70 / 101


Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance protected

Java Method Overriding


During inheritance in Java, if the same method is present in
both the superclass and the subclass. Then, the method in the
subclass overrides the same method in the superclass. This is
called method overriding.
1 class Language {
2 public void displayInfo () {
3 System . out . println ( " Common English Language " ) ;
4 }
5 }
6
7 class Java extends Language {
8 @Override
9 public void displayInfo () {
10 System . out . println ( " Java Programming Language " ) ;
11 }
12 }

./code/MethodPolymorphism.java

Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 71 / 101


Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance protected

Java Method Overriding

12
13 class Main {
14 public static void main ( String [] args ) {
15
16 // create an object of Java class
17 Java j1 = new Java () ;
18 j1 . displayInfo () ;
19
20 // create an object of Language class
21 Language l1 = new Language () ;
22 l1 . displayInfo () ;
23 }
24 }

./code/MethodPolymorphism.java

Note: The method that is called is determined during the exe-


cution of the program. Hence, method overriding is a run-time
polymorphism.

Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 72 / 101


Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance protected

2. Java Method Overloading


1 class Pattern {
2 // method without parameter
3 public void display () {
4 for ( int i = 0; i < 10; i ++) {
5 System . out . print ( " * " ) ;
6 } }
7 // method with single parameter
8 public void display ( char symbol ) {
9 for ( int i = 0; i < 10; i ++) {
10 System . out . print ( symbol ) ;
11 } } }
12 class Main {
13 public static void main ( String [] args ) {
14 Pattern d1 = new Pattern () ;
15 // call method without any argument
16 d1 . display () ;
17 System . out . println ( " \ n " ) ;
18 // call method with a single argument
19 d1 . display ( ’# ’) ;
20 } }

./code/MethodOverloadingExample.java
Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 73 / 101
Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance protected

Java Operator Overloading

Note: The method that is called is determined by the compiler.


Hence, it is also known as compile-time polymorphism.
In languages like C++, we can define operators to work
differently for different operands. However, Java doesn’t
support user-defined operator overloading.

Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 74 / 101


Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance protected

Polymorphic Variables

A variable is called polymorphic if it refers to different values


under different conditions.
Object variables (instance variables) represent the behavior of
polymorphic variables in Java. It is because object variables of a
class can refer to objects of its class as well as objects of its
subclasses.

Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 75 / 101


Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance protected

Polymorphic Variables
1 class P r o g r a m m i n g L a n g u a g e {
2 public void display () {
3 System . out . println ( " I am Programming Language . " ) ; } }
4 class Java extends P r o g r a m m i n g L a n g u a g e {
5 @Override
6 public void display () {
7 System . out . println ( " I am Object - Oriented Programming
Language . " ) ;
8 } }
9 class Main {
10 public static void main ( String [] args ) {
11 // declare an object variable
12 P r o g r a m m i n g L a n g u a g e pl ;
13 // create object of P r o g r a m m i n g L a n g u a g e
14 pl = new P r o g r a m m i n g L a n g u a g e () ;
15 pl . display () ;
16 // create object of Java class
17 pl = new Java () ;
18 pl . display () ;
19 } }

./code/PolymorphicVariable.java
Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 76 / 101
Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance protected

Polymorphic Variables

In the above example, we have created an object variable pl of


the ProgrammingLanguage class. Here, pl is a polymorphic
variable. This is because
In statement pl = new ProgrammingLanguage(), pl refer to the
object of the ProgrammingLanguage class.
And, in statement pl = new Java(), pl refer to the object of the Java
class.
This is an example of upcasting in Java.

Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 77 / 101


Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance protected

Java Encapsulation

Encapsulation is one of the key features of object-oriented


programming. Encapsulation refers to the bundling of fields and
methods inside a single class.
It prevents outer classes from accessing and changing fields and
methods of a class. This also helps to achieve data hiding.
Note: We often consider encapsulation as data hiding, but that’s
not entirely true.
Encapsulation refers to the bundling of related fields and
methods together. This can be used to achieve data hiding.
Encapsulation in itself is not data hiding.

Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 78 / 101


Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance protected

Example: Java Encapsulation


1 class Area {
2 // fields to calculate area
3 int length ;
4 int breadth ;
5 // constructor to initialize values
6 Area ( int length , int breadth ) {
7 this . length = length ;
8 this . breadth = breadth ; }
9 // method to calculate area
10 public void getArea () {
11 int area = length * breadth ;
12 System . out . println ( " Area : " + area ) ;
13 }
14 }
15 class Main {
16 public static void main ( String [] args ) {
17 // create object of Area
18 // pass value of length and breadth
19 Area rectangle = new Area (5 , 6) ;
20 rectangle . getArea () ;
21 }
22 }
Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 79 / 101
Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance protected

Why Encapsulation?

In Java, encapsulation helps us to keep related fields and


methods together, which makes our code cleaner and easy to
read.
It helps to control the values of our data fields.
1 class Person {
2 private int age ;
3
4 public void setAge ( int age ) {
5 if ( age >= 0) {
6 this . age = age ;
7 }
8 }
9 }

The getter and setter methods provide read-only or write-only


access to our class fields.

Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 80 / 101


Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance protected

Why Encapsulation?

We can also achieve data hiding using encapsulation. In the


above example, if we change the length and breadth variable
into private, then the access to these fields is restricted.
And, they are kept hidden from outer classes. This is called data
hiding.

Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 81 / 101


Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance protected

Data Hiding
Data hiding is a way of restricting the access of our data mem-
bers by hiding the implementation details. Encapsulation also
provides a way for data hiding.
We can use access modifiers to achieve data hiding.
1 class Person {
2 // private field
3 private int age ;
4 // getter method
5 public int getAge () {
6 return age ;
7 }
8 // setter method
9 public void setAge ( int age ) {
10 this . age = age ;
11 }
12 }

./code/DataHiding.java

Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 82 / 101


Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance protected

Example: Data hiding using the private spec-


ifier

13
14 class Main {
15 public static void main ( String [] args ) {
16
17 // create an object of Person
18 Person p1 = new Person () ;
19
20 // change age using setter
21 p1 . setAge (24) ;
22
23 // access age using getter
24 System . out . println ( " My age is " + p1 . getAge () ) ;
25 }
26 }

./code/DataHiding.java

Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 83 / 101


Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance protected

Java Nested and Inner Class

In Java, you can define a class within another class. Such class
is known as nested class
1 class OuterClass {
2 // ...
3 class NestedClass {
4 // ...
5 }
6 }

There are two types of nested classes you can create in Java.
Non-static nested class (inner class)
Static nested class

Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 84 / 101


Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance protected

Non-Static Nested Class (Inner Class)

A non-static nested class is a class within another class. It has


access to members of the enclosing class (outer class). It is
commonly known as inner class Since the inner class exists within
the outer class, you must instantiate the outer class first, in order to
instantiate the inner class.

Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 85 / 101


Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance protected

Example 1: Inner Class

1 class CPU {
2 double price ;
3 // nested class
4 class Processor {
5
6 // members of nested class
7 double cores ;
8 String manufacturer ;
9
10 double getCache () {
11 return 4.3;
12 }
13 }
14 // nested protected class

./code/InnerClass.java

Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 86 / 101


Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance protected

Example 1: Inner Class

15 protected class RAM {


16 // members of protected nested class
17 double memory ;
18 String manufacturer ;
19
20 double getClockSpeed () {
21 return 5.5;
22 }
23 }
24 }

./code/InnerClass.java

Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 87 / 101


Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance protected

Example 1: Inner Class


15 public class Main {
16 public static void main ( String [] args ) {
17
18 // create object of Outer class CPU
19 CPU cpu = new CPU () ;
20
21 // create an object of inner class Processor using
outer class
22 CPU . Processor processor = cpu . new Processor () ;
23
24 // create an object of inner class RAM using outer
class CPU
25 CPU . RAM ram = cpu . new RAM () ;
26 System . out . println ( " Processor Cache = " + processor .
getCache () ) ;
27 System . out . println ( " Ram Clock speed = " + ram .
getClockSpeed () ) ;
28 }
29 }

./code/InnerClass.java

Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 88 / 101


Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance protected

Accessing Members of Outer Class within


Inner Class
We can access the members of the outer class by using this
keyword.
1 class Car {
2 String carName ;
3 String carType ;
4
5 // assign values using constructor
6 public Car ( String name , String type ) {
7 this . carName = name ;
8 this . carType = type ;
9 }
10
11 // private method
12 private String getCarName () {
13 return this . carName ;
14 }

./code/AccessInnerClass.java

Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 89 / 101


Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance protected

Accessing Members of Outer Class within


Inner Class
16 // inner class
17 class Engine {
18 String engineType ;
19 void setEngine () {
20 // Accessing the carType property of Car
21 if ( Car . this . carType . equals ( " 4 WD " ) ) {
22 // Invoking method getCarName () of Car
23 if ( Car . this . getCarName () . equals ( " Crysler " ) )
{
24 this . engineType = " Smaller " ;
25 } else {
26 this . engineType = " Bigger " ;
27 }
28 } else {
29 this . engineType = " Bigger " ;
30 }
31 }
32 String getEngineType () {
33 return this . engineType ;
34 }
35 }
Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 90 / 101
Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance protected

Accessing Members of Outer Class within


Inner Class
37
38 public class Main {
39 public static void main ( String [] args ) {
40 // create an object of the outer class Car
41 Car car1 = new Car ( " Mazda " , " 8 WD " ) ;
42 // create an object of inner class using the outer
class
43 Car . Engine engine = car1 . new Engine () ;
44 engine . setEngine () ;
45 System . out . println ( " Engine Type for 8 WD = " + engine .
getEngineType () ) ;
46
47 Car car2 = new Car ( " Crysler " , " 4 WD " ) ;
48 Car . Engine c2engine = car2 . new Engine () ;
49 c2engine . setEngine () ;
50 System . out . println ( " Engine Type for 4 WD = " +
c2engine . getEngineType () ) ;
51 }
52 }

./code/AccessInnerClass.java
Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 91 / 101
Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance protected

Static Nested Class

In Java, we can also define a static class inside another class.


Such class is known as static nested class. Static nested classes
are not called static inner classes
Unlike inner class, a static nested class cannot access the mem-
ber variables of the outer class. It is because the static nested
class doesn’t require you to create an instance of the outer
class.
1 OuterClass . NestedClass obj = new OuterClass . NestedClass () ;

Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 92 / 101


Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance protected

Example: Static Inner Class


1 class MotherBoard {
2 // static nested class
3 static class USB {
4 int usb2 = 2;
5 int usb3 = 1;
6 int getTotalPorts () {
7 return usb2 + usb3 ;
8 }
9 }
10 }
11 public class Main {
12 public static void main ( String [] args ) {
13 // create an object of the static nested class
14 // using the name of the outer class
15 MotherBoard . USB usb = new MotherBoard . USB () ;
16 System . out . println ( " Total Ports = " + usb .
getTotalPorts () ) ;
17 }
18 }

./code/StaticInnerClass.java

Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 93 / 101


Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance protected

Example: Accessing members of Outer class


inside Static Inner Class
1 class MotherBoard {
2 String model ;
3 public MotherBoard ( String model ) {
4 this . model = model ;
5 }
6 // static nested class
7 static class USB {
8 int usb2 = 2;
9 int usb3 = 1;
10 int getTotalPorts () {
11 // accessing the variable model of the outer
classs
12 if ( MotherBoard . this . model . equals ( " MSI " ) ) {
13 return 4;
14 }
15 else {
16 return usb2 + usb3 ;
17 }
18 }
19 }
20 } Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 94 / 101
Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance protected

Example: Accessing members of Outer class


inside Static Inner Class

21 public class Main {


22 public static void main ( String [] args ) {
23
24 // create an object of the static nested class
25 MotherBoard . USB usb = new MotherBoard . USB () ;
26 System . out . println ( " Total Ports = " + usb .
getTotalPorts () ) ;
27 }
28 }

./code/AccessOuterClassInsideStaticClass.java

Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 95 / 101


Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance protected

Key Points to Remember

Java treats the inner class as a regular member of a class. They


are just like methods and variables declared inside a class.
Since inner classes are members of the outer class, you can
apply any access modifiers like private, protected to your inner
class which is not possible in normal classes.
Since the nested class is a member of its enclosing outer class,
you can use the dot (.) notation to access the nested class and
its members.
Using the nested class will make your code more readable and
provide better encapsulation.
Non-static nested classes (inner classes) have access to other
members of the outer/enclosing class, even if they are declared
private.

Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 96 / 101


Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance protected

Java Packages

A package in Java is used to group related classes. Think of it


as a folder in a file directory.
We use packages to avoid name conflicts, and to write a better main-
tainable code. Packages are divided into two categories:
Built-in Packages (packages from the Java API)
User-defined Packages (create your own packages)

Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 97 / 101


Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance protected

Built-in Packages

The Java API is a library of prewritten classes, that are free to


use, included in the Java Development Environment
The library is divided into packages and classes. Meaning you can
either import a single class (along with its methods and attributes),
or a whole package that contain all the classes that belong to the
specified package.
To use a class or a package from the library, you need to use the
import keyword
1 import package . name . Class ; // Import a single class
2 import package . name .*; // Import the whole package

Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 98 / 101


Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance protected

User-defined Packages

To create your own package, you need to understand that Java uses
a file system directory to store them. Just like folders on your com-
puter
To create a package, use the package keyword:
1 package mypack ;
2 class My Packag eClass {
3 public static void main ( String [] args ) {
4 System . out . println ( " This is my package ! " ) ;
5 }
6 }

Save the file as MyPackageClass.java, and compile it.

Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 99 / 101


Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance protected

Compile and run package in JAVA

Save the file as MyPackageClass.java, and compile it: javac


MyPackageClass.java
Then compile the package: javac -d . MyPackageClass.java
This forces the compiler to create the "mypack" package
The -d keyword specifies the destination for where to save the
class file. You can use any directory name, like c:/user
(windows), or, if you want to keep the package within the same
directory, you can use the dot sign ".", like in the example above.
To run: java mypack.MyPackageClass

Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 100 / 101


Java Inheritance Types of inheritance Java Method Overriding Access Specifiers in Method Overriding super Keyword in Java Inheritance protected

Dr. Nikhil Mhala

Contact:
[email protected]
Landline: 0863-2370961 (Mon-Fri 9 am - 5 pm)
Extension: 5961

Dr. Nikhil Mhala VIT-AP CSE1012 May 8, 2022 101 / 101

You might also like