In this lesson, you will learn
Core Concept:
How it Works:
extends keyword is used to implement single inheritance.

package ch9.l3;
//Create a superclass.
class A {
int i, j;
void setij(int i,int j) {
this.i=i;
this.j=j;
}
void showij() {
System.out.println("i and j: " + i + " " + j);
}
}
//Create a subclass by extending class A.
class B extends A {
int k;
void setk(int k) {
this.k=k;
}
void showk() {
System.out.println("k: " + k);
}
void sum() {
System.out.println("i+j+k: " + (i+j+k));
}
}
public class SingleInheritance {
public static void main(String[] args) {
A objA=new A();
B objB=new B();
//The superclass may be used by itself.
objA.setij(10, 20);
System.out.println("Contents of Super Class A: ");
objA.showij();
System.out.println();
/* The subclass can access to all public members of
its superclass. */
objB.setij(5, 6);
objB.setk(7);
System.out.println("Contents of Sub Class B: ");
objB.showij();
objB.showk();
System.out.println("Sum of i, j and k in Subclass Object:");
objB.sum();
}
}
Contents of Super Class A:
i and j: 10 20
Contents of Sub Class B:
i and j: 5 6
k: 7
Sum of i, j and k in Subclass Object:
i+j+k: 18
package ch9.l3;
//Superclass
class Vehicle {
protected String brand = "Ford"; // Vehicle attribute
public void honk() { // Vehicle method
System.out.println("Tuut, tuut!");
}
}
//Subclass
class Car extends Vehicle {
private String modelName = "Mustang"; // Car attribute
public void display() {
System.out.println("Brand: " + brand + ", Model Name: " + modelName);
}
}
//Main class
public class VehicleMain {
public static void main(String[] args) {
Car myCar = new Car();
myCar.honk();
myCar.display();
}
}
Tuut, tuut!
Brand: Ford, Model Name: Mustang
In Java, a protected member of a class is accessible:
Create a Bank class with a protected attribute balance. Include a method showBalance() that prints the balance. Then, define a subclass SavingsAccount that inherits Bank and includes a methoddeposit(int amount) to add to the balance. Demonstrate depositing an amount and showing the balance.
class Bank {
protected int balance;
Bank() {
balance = 0;
}
void showBalance() {
System.out.println("Current Balance: $" + balance);
}
}
class SavingsAccount extends Bank {
void deposit(int amount) {
balance += amount;
}
}
public class Main {
public static void main(String[] args) {
SavingsAccount myAccount = new SavingsAccount();
myAccount.deposit(500); // Deposit $500
myAccount.showBalance(); // Prints "Current Balance: $500"
}
}
There are no reviews yet. Be the first one to write one.
You must be logged in to submit a review.