Java Extends Keyword Example
In this tutorial, we will explain the Java extends keyword. By using this keyword, a subclass implements the extension of its parent class properties.
1. Introduction
The Object
class, defined in the Java lang package defines and implements behavior common to all classes-including the ones that you write. In the Java platform, many classes derive directly from Object
, other classes derive from some of those classes, and so on, forming a hierarchy of classes.
In Java, a subclass can extend the properties of its parent class by using the extends
keyword. Generally, in Java:
java.lang.Object
is the parent class of all classes. Do note, this is implicit and does not require to be specified explicitly- A class can only extend a single class and Multiple Inheritance is not allowed
Let us understand this with a simple code snippet.
Code Snippet 1
01 02 03 04 05 06 07 08 09 10 | package com.jcg.example; class Parent { } public class Snippet extends Parent { } |
In the snippet example, the class Snippet is a subclass of class Parent. As a subclass, class Snippet inherits (i.e. extends) the variables and methods from class Parent. Similarly, the extends
keyword is also used in an interface declaration to specify one or more super interfaces. For instance.
Code Snippet 2
1 2 3 4 5 6 7 8 9 | package com.jcg.example; interface ParentInterface { . . . . . } public interface ChildInterface extends ParentInterface { . . . . . } |
Now, let us go ahead and understand these snippets with the help of real-time examples. For easy usage, I am using Eclipse Ide.
2. Java Extends Keyword Example
In this example, I have created a base class and a subclass that extends the property and the method of the base class. For a better understanding, developers can execute the below code in Eclipse Ide.
Example 1
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | package com.jcg.example; class Base { public int x = 1 ; public int getX() { return x; } } class Subclass extends Base { } public class Example1 { public static void main(String[] args) { Subclass subClass = new Subclass(); System.out.println(subClass.x); System.out.println(subClass.getX()); } } |
Output
1 1
That is all for this tutorial and I hope the article served you whatever you were looking for. Happy Learning and do not forget to share!
3. Conclusion
In this tutorial, we had an in-depth look at the extends
keyword. By using this keyword, a subclass implements the extension of its parent class properties. You can download the sample application as an Eclipse project in the Downloads section.
4. Download the Eclipse Project
This was an example of extends keyword in Java.
You can download the full source code of this example here: Java Extends Keyword Example