java
java
class Calculation {
int z;
javac My_Calculation.java
java My_Calculation
Output
If you consider the above program, you can instantiate the class as
given below. But using the superclass reference variable ( cal in this
case) you cannot call the method multiplication(), which belongs to
the subclass My_Calculation.
super.variable
super.method();
Sample Code
Example
class Super_class {
int num = 20;
Compile and execute the above code using the following syntax.
javac Super_Demo
java Super
super(values);
Sample Code
Copy and paste the following program in a file with the name
Subclass.java
Example
class Superclass {
int age;
Superclass(int age) {
this.age = age;
}
Compile and execute the above code using the following syntax.
javac Subclass
java Subclass
Output
IS-A Relationship
IS-A is a way of saying: This object is a type of that object. Let us
see how the extends keyword is used to achieve inheritance.
With the use of the extends keyword, the subclasses will be able to
inherit all the properties of the superclass except for the private
properties of the superclass.
Example
class Animal {
}
Output
true
true
true
Example
Example
interface Animal{}
class Mammal implements Animal{}
Output
true
true
true
HAS-A relationship
These relationships are mainly based on the usage. This determines
whether a certain class HAS-A certain thing. This relationship helps
to reduce duplication of code as well as bugs.
Example
public class Vehicle{}
public class Speed{}
This shows that class Van HAS-A Speed. By having a separate class
for Speed, we do not have to put the entire code that belongs to
speed inside the Van class, which makes it possible to reuse the
Speed class in multiple applications.
The inheritance in which there is only one base class and one
derived class is known as single inheritance. The single (or, single-
single
level) inheritance inherits data from only one base class to only one
derived class.
class One {
public void printOne() {
System.out.println("printOne() method of One class.");
}
}
// Calling method
obj.printOne();
}
}
Output
class One {
public void printOne() {
System.out.println("printOne() method of One class.");
}
}
// Calling methods
obj.printOne();
obj.printTwo();
}
}
Output
The inheritance in which only one base class and multiple derived
classes is known as hierarchical inheritance.
// Base class
class One {
public void printOne() {
System.out.println("printOne() Method of Class One");
}
}
// Derived class 1
class Two extends One {
public void printTwo() {
System.out.println("Two() Method of Class Two");
}
}
// Derived class 2
class Three extends One {
public void printThree() {
System.out.println("printThree() Method of Class Three");
}
}
// Testing CLass
public class Main {
public static void main(String args[]) {
Two obj1 = new Two();
Three obj2 = new Three();
Output
Example