Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

The idea of inheritance is simple but powerful: When you want to create a new class and there is already a class that includes some of the code that you want, you can derive your new class from the existing class. In doing this, you can reuse the fields and methods of the existing class without having to write (and debug!) them yourself.

A subclass inherits all the members (fields, methods, and nested classes) from its superclass. Constructors are not members, so they are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass.

In contrast to Python, Java supports only object-oriented programming, while Python supports many (but not all) aspects of object-oriented programming; but it is possible to write a Python program without making any use of OO concepts.

An Example of Inheritance

Here is the sample code for a possible implementation of a Animal class , both in Java and Python.

Code Block
languagejava
titleClass implementation in Java
class Animal{
	private String name;
	public Animal(String name){
		this.name = name;
	}
	public void saySomething(){
		System.out.println("I am " + name);
	}
}
Code Block
languagepy
titleClass implementation in Python
class Animal():
        def __init__(self, name):
            self.name = name
 
        def saySomething(self):
            print "I am " + self.name    

A class declaration for a Dog class that is a subclass of Animal might look like this. 

Code Block
languagejava
titleStrings in Java
 class Dog extends Animal{
	public Dog(String name) {
		super(name);
	}	
	public void saySomething(){
		System.out.println("I can bark");
	}
}
 
public class Main {
	public static void main(String[] args) {
		Dog dog = new Dog("Chiwawa");
		dog.saySomething();
 
	}
}
Code Block
languagepy
titleStrings in Python
class Dog(Animal):
        def saySomething(self):
            print "I am "+ self.name \
            + ", and I can bark"
 
dog = Dog("Chiwawa") 
dog.saySomething()

Dog inherits all the fields and methods of Animal and can provide additional field(s) and method(s) to set it. Except for the constructor, it is as if you had written a new dog class entirely from scratch, with one field and two methods. However, you didn't have to do all the work. This would be especially valuable if the methods in the Animal class were complex and had taken substantial time to debug.

When you extend a base class, there is no requirement such as defining an explicit constructor for implicit super constructor.