0% found this document useful (0 votes)
11 views27 pages

Inheritance

The document explains the concept of inheritance in Java, detailing subclasses and superclasses, and various types of inheritance such as single, multilevel, hierarchical, and multiple inheritance through interfaces. It also covers encapsulation, emphasizing the importance of data hiding and providing getter and setter methods for private variables. Additionally, it includes practical examples and questions related to implementing these concepts in programming scenarios.

Uploaded by

mirshakishok
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views27 pages

Inheritance

The document explains the concept of inheritance in Java, detailing subclasses and superclasses, and various types of inheritance such as single, multilevel, hierarchical, and multiple inheritance through interfaces. It also covers encapsulation, emphasizing the importance of data hiding and providing getter and setter methods for private variables. Additionally, it includes practical examples and questions related to implementing these concepts in programming scenarios.

Uploaded by

mirshakishok
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 27

Inheritance

Inheritance (Subclass and


Superclass)
• In Java, it is possible to inherit attributes and methods from one class
to another.
• We group the "inheritance concept" into two categories:

subclass (child) - the class that inherits from another class

superclass (parent) - the class being inherited from

• To inherit from a class, use the extends keyword.


class Vehicle {
protected String brand = “Volswagen"; // Vehicle attribute
public void honk() { // Vehicle method
System.out.println(“whistle!");
}
}

class Car extends Vehicle {


private String modelName = “vento"; // Car attribute
public static void main(String[] args) {

// Create a myCar object


Car myCar = new Car();

// Call the honk() method (from the Vehicle class) on the myCar object
myCar.honk();

// Display the value of the brand attribute (from the Vehicle class) and the value of the modelName from the Car class
System.out.println(myCar.brand + " " + myCar.modelName);
}
The final Keyword

• If you don't want other classes to inherit from a class, use the final keyword
final class Vehicle {
...
}

class Car extends Vehicle {


...
}

Output

Main.java:9: error: cannot inherit from final Vehicle


class Main extends Vehicle {
^
1 error)
Types of inheritance

• Single Inheritance
• In single inheritance, a single subclass extends from a single superclass.
import java.io.*;
import java.lang.*;
import java.util.*;
class One {
public void print_geek()
{
System.out.println("Geeks");
}}
class Two extends One {
public void print_for() { System.out.println("for"); }}
public class Main {
public static void main(String[] args)
{
Two g = new Two();
g.print_geek();
g.print_for();
g.print_geek();
}
}
Multilevel Inheritance

• In multilevel inheritance, a subclass extends from a superclass and then


the same subclass acts as a superclass for another class.
// Importing required libraries
import java.io.*;
import java.lang.*;
import java.util.*;
// Parent class One
class One {
// Method to print "Geeks"
public void print_geek() {
System.out.println("Geeks");
}
}
// Child class Two inherits from class One
class Two extends One {
// Method to print "for"
public void print_for() {
System.out.println("for");
}
}
// Child class Three inherits from class Two
class Three extends Two {
public void print_lastgeek() {
System.out.println("Geeks");
}
// Driver class
public class Main {
public static void main(String[] args) {
// Creating an object of class Three
Three g = new Three();
// Calling method from class One
g.print_geek();

// Calling method from class Two


g.print_for();

// Calling method from class Three


g.print_lastgeek();
}
}
Hierarchical Inheritance

• In hierarchical inheritance, multiple subclasses extend from a single


superclass
class A {
public void print_A() { System.out.println("Class A"); }
}

class B extends A {
public void print_B() { System.out.println("Class B"); }
}

class C extends A {
public void print_C() { System.out.println("Class C"); }

class D extends A {
public void print_D() { System.out.println("Class D"); }
}
// Driver Class
public class Test {
public static void main(String[] args)
{
B obj_B = new B();
obj_B.print_A();
C obj_C = new C();
obj_C.print_A();
obj_C.print_C();

D obj_D = new D();


obj_D.print_A();
obj_D.print_D();
}
}
Multiple Inheritance(through interface)

• In multiple inheritance, a single subclass extends from multiple


superclasses
// Interface 1 that defines coding behavior
interface Coder {
void writeCode();
}

// Interface 2 that defines testing behavior


interface Tester {
void testCode();
}

// Class implementing both interfaces


class DevOpsEngineer implements Coder, Tester {
@Override
public void writeCode() {
System.out.println("DevOps Engineer writes automation scripts.");
}

• @Override
• public void testCode() {
• System.out.println("DevOps Engineer tests deployment pipelines.");
• } // Additional method specific to DevOpsEngineer
public void deploy() {
System.out.println("DevOps Engineer deploys code to cloud.");
}
// Driver class
public class Main {
public static void main(String[] args) {
DevOpsEngineer devOps = new DevOpsEngineer();

devOps.writeCode();
devOps.testCode();
devOps.deploy();
}
}
Questions for all types inheritance
• In a library management system, you have Book as a base class with title, author, and isbn. You also have Journal
with issueNumber and publisher. Both can be considered LibraryItems. How would you model this using
inheritance, ensuring that common functionalities like displayDetails() are shared, and specific attributes are
handled appropriately?
• Concepts used:
• Hierarchical inheritance, common methods in superclass, specific attributes in subclasses.

• Question:In a university system, there are different types of people: Student, Teacher, and
Administrator. All of them have common details like name and ID, but different roles:A Student has a
course and marks.A Teacher has a subject and salary.An Administrator has a department and
duty.Create an inheritance hierarchy using a base class Person. Include a method showRole() that
prints each person’s role details.
• Key Concepts:
Base class: Person
Subclasses: Student, Teacher, Administrator
Method overriding: showRole()
Encapsulation

• The meaning of Encapsulation, is to make sure that "sensitive" data is


hidden from users.

• declare class variables/attributes as private

• provide public get and set methods to access and update the value of a
private variable
Why Encapsulation?

• Better control of class attributes and methods


• Class attributes can be made read-only (if you only use the get
method), or write-only (if you only use the set method)
• Flexible: the programmer can change one part of the code without
affecting other parts
• Increased security of data
Get and Set
• You learned from the previous chapter that private variables can only be
accessed within the same class (an outside class has no access to it).
However, it is possible to access them if we provide public get and set
methods.

• The get method returns the variable value, and the set method sets the
value.

• Syntax for both is that they start with either get or set, followed by the
name of the variable, with the first letter in upper case:
Example

public class Person {


private String name; // private = restricted access

// Getter
public String getName() {
return name;
}

// Setter
public void setName(String newName) {
this.name = newName;
}
}
explaination

• The get method returns the value of the variable name.

• The set method takes a parameter (newName) and assigns it to the


name variable. The this keyword is used to refer to the current object.

• However, as the name variable is declared as private, we cannot


access it from outside this class:
Example

public class Main {


public static void main(String[] args) {
Person myObj = new Person();
myObj.name = "John"; // error
System.out.println(myObj.name); // error
}
}
• Instead, we use the getName() and setName() methods to access and update the
variable:

• Example
public class Main {
public static void main(String[] args) {
Person myObj = new Person();
myObj.setName("John"); // Set the value of the name variable to "John"
System.out.println(myObj.getName());
}
}

• // Outputs "John"
programs
• Create an Employee class with:
name (String)
id (int)
basicSalary (double)
Provide setters and getters.
Add a method calculateNetSalary() which adds:
20% HRA
10% DA
Demonstrate encapsulation and salary computation in the main method.
Product Inventory
• Model a class
Product that stores:productId (int)
productName (String)
price (double)
quantityInStock (int)
Write setter/getters. Validate
price and quantity should be non-negative.
Add a method isAvailable() that returns true if quantity is greater than 0.
You are building a simple banking system. Your task is to implement a BankAccount class using encapsulation
principles. That means all the data members should be private, and access should only be allowed via public getters
and setters.
Class Details
Create a class named BankAccount with the following
private fields:String accountHolderName
String accountNumber
double balance
Method Description
void setAccountHolderName(String name) Sets the account holder's name
String getAccountHolderName() Returns the account holder's name
void setAccountNumber(String accNo) Sets the account number
String getAccountNumber() Returns the account number
void deposit(double amount) Adds amount to balance (if amount is > 0)
void withdraw(double amount) Deducts amount from balance (if amount is <= balance)
double getBalance() Returns the current balance
Input Format
• The first line contains the name of the account holder.
• The second line contains the account number.
• The third line contains a deposit amount.The fourth line contains a withdrawal amount.
• John Doe
• ACC12345
• 1000
• 500
• Sample Output
• Account Holder: John Doe
• Account Number: ACC12345
• Final Balance: 500.0

You might also like