I just started to learn java, so now i read about such possibility as inheritance, so try to create class that must create object - box. And using inheritance implement new properties to created object. I try to put each class in separate file, so after creating class, try to use it in
public static void main(String[] args)
So class Inheritance:
public class Inheritance {
double width;
double height;
double depth;
Inheritance (Inheritance object){
width = object.width;
height = object.height;
depth = object.depth;
}
Inheritance ( double w, double h, double d){
width = w;
height = h;
depth = d;
}
Inheritance (){
width = -1;
height = -1;
depth = -1;
}
Inheritance (double len){
width=height=depth=len;
}
double volumeBox (){
return width*height*depth;
}
class BoxWeight extends Inheritance {
double weight;
BoxWeight (double w, double h, double d, double m){
super(w,h,d);
weight = m;
}
}
But, when i try to use BoxWeight in main class, during using i got an error
public class MainModule {
public static void main(String[] args) {
Inheritance.BoxWeight mybox1 = new Inheritance.BoxWeight(9, 9, 9, 9);
....
Error - No enclosing instance of type Inheritance is accessible. Where i'm wrong?
Inheritance is the procedure in which one class inherits the attributes and methods of another class. The class whose properties and methods are inherited is known as the Parent class. And the class that inherits the properties from the parent class is the Child class.
Main disadvantage of using inheritance is that the two classes (base and inherited class) get tightly coupled. This means one cannot be used independent of each other.
As it stands, BoxWeight
requires an instance of Inheritance
to work (just like accessing a non-static variable or function requires an instance, so accessing a non-static inner class also does). If you change it to static
it would work, but this isn't required.
BoxWeight
doesn't need to be inside the Inheritance
class.
Instead, remove BoxWeight
out of the Inheritance
class.
And change Inheritance.BoxWeight
to BoxWeight
.
EDIT: Just for completeness, you could also make it:
Inheritance.BoxWeight mybox1 = new Inheritance().new BoxWeight(...);
Inheritance.BoxWeight
is just the type, so the above does not apply. But to create an instance of BoxWeight
, you need an Inheritance
object, which you create with new Inheritance()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With