What does the extends key word mean in java? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 7

What does the extends key word mean in java?

extends

6th Nov 2016, 3:21 AM
David Kariuki
David Kariuki - avatar
2 Answers
+ 7
Java, like other object-orientated languages, supports class inheritance. Inheritance allows one class to "inherit" the properties of another class. For example, all Java objects are inherited from the java.lang.Object class. This means that we can call the toString() method inherited from java.lang.Object, and get a string representation of any java object, such as an Integer, a Float, a Double, etc. Take a look at the following example, which demonstrates the use of the 'extends' keyword. public class A extends java.lang.Object { public int number; public String toString() { return new String("Value : " + number); } } In this example, we implicitly state that we extend java.lang.Object, and override the functionality of the toString() method by providing our own function. Note that all classes, whether they state so or not, will be inherit from java.lang.Object. Our next example shows a more common use of the keyword 'extends'. In this example, we inherit from class A, which means that B will also contain a field called number, and a function called toString(). public class B extends A { public void increment() { number++; } } public class ABDemo { public static void main (String args[]) { // Create an instance of B B counter = new B(); // Increment B counter.increment(); // Call toString() method System.out.println ( counter.toString() ); } } Even though we never defined a toString() method, or added a number field to the B class, it has inherited this information from A. This is a powerful feature of object-orientated programming, and can save significant time when developing classes.
6th Nov 2016, 3:21 AM
David Kariuki
David Kariuki - avatar
+ 1
The extends keyword enables the subclass you write it in to inherit attributes...more like variables...and method from a parent class. After inheriting, you can access all that is in the parent class. The subclass has to be instantiated so as to inherit constructors. I thinks the significance of all this is that it kind of makes your code easier to read...that is, instead of having so many codes in a single class, you can have related ones in subclasses and call the subclasses in the main class(only class with the main method).......Java on ya'll.
18th Nov 2016, 10:25 PM
Allan Erissat
Allan Erissat - avatar