JAVA Unit-4
JAVA Unit-4
// Creating a superclass.
public class BaseClass { public class InheritanceTest {
void features() public static void main(String[] args)
{
{ // Create an object of the derived class.
System.out.println("Feature A"); DerivedClass d = new DerivedClass();
System.out.println("Feature B");
// Call features() method from the derived class using object
} } reference variable d.
// Creating a subclass. d.features();
public class DerivedClass extends BaseClass {
// Call ownFeature() method using reference variable d.
void ownFeature() d.ownFeature();
{ }
}
System.out.println("Feature C");
}
}
Inheritable Members of Why do We Use
Classes
Inheritance in Java?
Types of Fields/Members Classes
• We can reuse the code from the base class.
Instance variables Yes • we can increase features of class or method by overriding.
Static variables Yes • Inheritance is used to use the existing features of class.
Abstract methods Yes
• It is used to achieve runtime polymorphism i.e method
overriding.
Instance methods Yes
• Using inheritance, we can organize the information in a
Static methods Yes
hierarchal form.
Constructor No
Initialization blocks No
Role of Constructor in Java
Inheritance
• The role of constructor in inheritance is that the constructor in the
superclass is responsible for building an object of superclass and the
constructor of subclass builds an object of subclass.
• We can call other constructors of same class using this keyword, but
you cannot call a subclass constructor from the superclass constructor.
Important Rules of Java
Inheritance
1. We cannot assign a superclass to the subclass.
2. We cannot extend the final class.
3. A class cannot extend itself.
4. One class can extend only a single class.
5. We cannot extend a class having a private constructor, but if we have private
constructor as well as public constructor, then we can extend superclass to subclass. In
this case, the only public constructor will work.
6. If we assign subclass reference to superclass reference, it is called dynamic method
dispatch in java.
7. Constructor, Static initialization block (SIB), and Instance initialization block (IIB) of the
superclass cannot be inherited to its subclass, but they are executed while creating an
object of the subclass.
8. A static method of superclass is inherited to the subclass as a static member and non-
static method is inherited as a non-static member only.
Superclass and Subclass Examples
public class Parentclass { public class Parentclass {
void m1() { void m1()
{
System.out.println("Superclass m1 method");
System.out.println("Superclass m1 method");
} } } }
public class Childclass extends Parentclass { public class Childclass extends Parentclass {
void m2() { void m2()
{
System.out.println("Childclass m2 method"); System.out.println("Childclass m2 method");
} } } }
public class Test { public class Test {
public static void main(String[] args)
public static void main(String[] args) {
{
// Creating an object of superclass. // Creating an object of subclass.
Parentclass p = new Parentclass(); Childclass c = new Childclass();
p.m1();
// Accessing superclass and subclass members using subclass
// Here, subclass members are not available to superclass. object reference variable.
// So, we cannot access them using superclass reference variable. c.m1();
c.m2();
} }
} }
// Subclass inheriting from Vehicle class.
// Base class
class Bicycle extends Vehicle
class Vehicle { {
String brand; Bicycle(String brand) {
super(brand);
Vehicle(String brand) {
}
this.brand = brand; } void pedal() {
void honk() { System.out.println("Pedaling the " + brand + " bicycle");
}}
System.out.println("Honk honk!");
}}
// Subclass inheriting from Vehicle class. public class Main {
public static void main(String[] args) {
class Car extends Vehicle { Car myCar = new Car("Toyota", "Corolla");
String model; Bicycle myBicycle = new Bicycle("Schwinn");
myCar.drive();
Car(String brand, String model) {
myCar.honk();
super(brand); System.out.println();
this.model = model; } myBicycle.pedal();
myBicycle.honk();
void drive() {
} }
System.out.println("Driving the " + brand + " " + model);
} }
Base class and Derived class Members with Same Name
how to access superclass members from the subclass?
public class Number { Answer with Super keyword
int x = 20; public class Number {
void display() { int x = 20;
System.out.println("X = " +x); Method void display() {
} } override System.out.println("X = " +x);
} }
public class Number2 extends Number {
public class Number2 extends Number {
int x = 50;
int x = 50;
void display() { void display() {
System.out.println("X = " +x); System.out.println("X = " +super.x);
}} System.out.println("X = " +x);
public class NumberTest { }}
public static void main(String[] args) public class NumberTest {
public static void main(String[] args)
{
{
// Creating an instance of subclass.
// Creating an instance of subclass.
Number2 n = new Number2(); Number2 n = new Number2();
n.display(); n.display();
}} }}
Types of Inheritance in Java
Based on class, there are three types of inheritance in Java.
They are as follows:
1. Simple/Single level Inheritance
2. Multiple Inheritance
3. Hybrid Inheritance
Note: multiple inheritance and hybrid inheritance are supported through the
interface only.
Single level public class A {
// Declare an instance method.
public void methodA() {
Inheritance System.out.println("Base class method");
} }
• A class is extended by only one class, it is
called single-level inheritance in Java or // Declare a derived class or subclass and extends class A.
simply single inheritance. public class B extends A {
public void methodB()
{
System.out.println("Child class method");
} }
Now, you need to understand why Java does not support multiple
inheritance through class.
Why Java does not Support Multiple Inheritance
through Classes?
class A {
void msg()
{
System.out.println("Hello Java");
}}
class B {
void msg()
{
System.out.println("Welcome you");
} }
• Super keyword in Java is a reference variable that refers to an immediate superclass object.
void m2() {
m1(this);
// Passing this as an argument in the m1 method. this keyword will pass the reference of current class
object to the m1 method.
}
• For example:
• abstract void msg(); // No body.
public abstract class MyTest {
public class MyClass {
abstract void calculate(int a, int b); // No body. public static void main(String[] args)
} {
public class Addition extends MyTest { // Creating objects of classes.
Addition a = new Addition();
void calculate(int a, int b) { Subtraction s = new Subtraction();
int x = a + b; Multiplication m = new Multiplication();
// Calling methods by passing argument values.
System.out.println(“Sum: ” +x); } a.calculate(20, 30);
} s.calculate(10, 5);
public class Subtraction extends MyTest { m.calculate(10, 20); }
}
void calculate(int a, int b) {
int y = a - b;
System.out.println(“Subtract: ” +y); }
}
public class Multiplication extends MyTest {
void calculate(int a, int b) {
int z = a * b;
System.out.println(“Multiply: ” +z); }
}
Features of Abstract class in
Java
• There are following important features of abstract class in Java that you should
keep in mind. They are as follows:
1. Abstract class is not a pure abstraction in Java.
2. In Java, object creation is not possible for an abstract class because it is a
partially implemented class, not fully implemented class.
3. It can be abstract even with no abstract method.
4. It can have one or more abstract methods or non-abstract methods (or concrete
methods) or a combination of both methods.
5. Abstract class allows to define private, final, static and concrete methods.
Everything is possible to define in an abstract class as per application requirements.
6. It can have constructors.
7. Abstract class does not support multiple inheritance in Java but allows in
interfaces.
8. It can implement one or more interfaces in Java.
public abstract class Hello {
public abstract class Employee {
// Declaration of instance method. private String name;
public void msg1() { private int id;
public Employee(String name, int id) {
System.out.println("msg1-Hello"); } this.name = name;
abstract public void msg2(); // abstract method. this.id = id; }
} // Declaration of concrete method.
void m1() {
public class Test extends Hello { System.out.println("Name: " +name);
// Overriding abstract method. System.out.println("Id: " +id); }
}
public void msg2() {
public class Engineer extends Employee {
System.out.println("msg2-Test"); } public Engineer(String name, int id) {
public static void main(String[] args) { super(name, id); // This statement is used to call super class
constructor.
// Creating object of subclass Test.
}
Test obj = new Test(); public static void main(String[] args) {
obj.msg1(); // Creating an object of the subclass of abstract class.
Engineer e = new Engineer(“Sri", 4000);
obj.msg2(); } e.m1();
} } }
public abstract class Identity {
public class Mainclass
abstract void getName(String name);
{
abstract void getGender(String gender); public static void main(String[] args)
abstract void getCity(String city); {
}
// Declaring abstract class reference equal to subclass
public class Person extends Identity object.
{
void getName(String name) Identity i = new Person();
i.getName(“SRI");
{ System.out.println("Name : " +name); }
i.getGender("MALE");
void getGender(String gender) i.getCity(“Shirpur");
{ System.out.println("Gender : " +gender); }
void getCity(String city) // This statement will generate a compile-time error
because
{ System.out.println("City: " +city); }
// we cannot access newly added method in subclass using
superclass reference.
// Newly added method in subclass. // i.getCountry("INDIA");
void getCountry(String country) }
}
{ System.out.println("Country: " +country); }
}
Interface in Java
class VehicleTypes {
interface Vehicle { public int getNoOfWheels(); }
}
class Bus implements VehicleTypes.Vehicle { public int getNoOfWheels() { return 6; } }
class Car implements VehicleTypes.Vehicle { public int getNoOfWheels() { return 4; } }
class Bike implements VehicleTypes.Vehicle { public int getNoOfWheels() { return 2; } }
public class VehicleTest {
public static void main(String[] args) {
Bus b = new Bus();
System.out.println(b.getNoOfWheels());
}
Difference between Class and
Interface in Java
CLASS INTERFACE
The ‘class’ keyword is used to create a class. The ‘interface’ keyword is used to create an interface.