Single Inheritance Example in Java
On this page (10sections)
Introduction
Single Inheritance is a classic Java console program that demonstrates the concept with complete source code and sample output. These programs cover your first Java class, constructors, methods and simple OOP building blocks.
This tutorial walks through the program line by line, explains how the logic works, and highlights best practices you can apply in your own code.
Definition
Single inheritance enables a derived class to inherit properties and behavior from a single parent class. It allows a derived class to inherit the properties and behavior of a base class, thus enabling code reusability as well as adding new features to the existing code. This makes the code much more elegant and less repetitive.
Syntax
class A{
//Do something
}
class B extends A{
//Do something
}
class C extends A{
//Do something
}
Single Inheritance Example Program
class SingleInheritance{
static int num1=10;
static int num2=5;
}
class MainInheritance extends SingleInheritance{
public static void main(String[] args){
int num3=2;
int result=num1+num2+num3;
System.out.println("Result of child class is "+result);
}
}
Sample Output
Result of child class is 17
When to use
Use this single inheritance example when learning or revising core Java syntax.
How it works
-
Execution begins in the
mainmethod — the JVM calls this method when you run the class. -
static int num1=10;updates a variable used in the calculation or output. -
static int num2=5;updates a variable used in the calculation or output. -
int num3=2;updates a variable used in the calculation or output. -
int result=num1+num2+num3;updates a variable used in the calculation or output. -
A
println/printcall writes text to the console — part of the sample output below. -
Compare your console output with the sample output for Single Inheritance to confirm the program behaves correctly.
Best Practices
- Name classes in PascalCase and follow one public class per file when starting out.
- Keep
mainshort — delegate work to other methods as programs grow.
Common Mistakes
- Copying code without understanding each line — practice by changing one statement at a time.
- Mismatching the public class name and the
.javafilename. - Forgetting semicolons at the end of statements.