Learn Java Programming - Introduction to Inheritance Tutorial

preview_player
Показать описание
Inheritance is one of the key components to understanding object-oriented programming. The word inheritance implies receiving certain possessions upon the death of a family member or a close friend. In real life, one can draw up a will specifying who will receive a possession and who will not. One can even designate that possessions can be shared or even say that nobody can have them. Many lawyers make a decent living writing up wills and acting as an executor.
In Java, the concept of inheritance is similar; the relatives are the classes, the possessions are its members, the family is a package. A will specifies the ownership and access to possessions, whereas in Java, the ownership and access to class members is handled by access modifiers. There is one major difference between real life and Java - no classes have to die for inheritance to occur. The topic of inheritance is quite extensive and will apply to many advanced features of Java. The goal of this tutorial is to lay the first building block in the foundation of understanding inheritance - the extends keyword.
The extends keyword 'ties' the members of a parent class to a child class. The extends keyword is placed after the name of the child class and before the name of the parent class that we are inheriting from. The parent class is known as the superclass and the child class is known as the subclass.
Рекомендации по теме
Комментарии
Автор

I went through all of your tutorials. Pretty amazing.
Regarding this tutorial, while going through it again, I realised that if I want a class to be inherited, I cannot define a constructor and overload it. Is that right? So I tried the following below:


CardboardBox cb1 = new CardboardBox(5, 5, 5, "inches", "brown");
class Box {
int length = 0;
int height = 0;
int width = 0;
String unitOfMeasurement = "";

Box(){
super();
}
Box(int length, int height, int width, String measurement_param) {
this.length = length;
this.height = height;
this.width = width;
this.unitOfMeasurement = measurement_param;
}
int returnVolume() {
return (length * height * width);
}
}

class CardboardBox extends Box { // Cardboard box is the child or subclass, Box is the parent or superclass

String color=""; // only member declared in the Cardboardbox class
// the 'extends Box' above inherits all of the members of the Box class
}

But I kept getting the error message:
required: no arguments
found: int, int, int, String, String
reason: actual and formal argument lists differ in length

Can you tell me why is it so? Because I thought it CardboardBox is inherting all features of Box class, then it should also inherit all the variables declared as well. So what is the problem in defining the constructor of the class being inherited?
Besides, if we want a class to be inherited, does it means that it cannot have an overloaded constructor?

Thanks again
Siddhartha

siddharthadas