In Java, I can't create instances of abstract classes. So why doesn't eclipse scream about the following code?
public abstract class FooType {
private final int myvar;
public FooType() {
myvar = 1;
}
}
3) Abstract class can have final, non-final, static and non-static variables. Interface has only static and final variables.
Abstract Classes Compared to Interfaces You cannot instantiate them, and they may contain a mix of methods declared with or without an implementation. However, with abstract classes, you can declare fields that are not static and final, and define public, protected, and private concrete methods.
Type of variables: Abstract class can have final, non-final, static and non-static variables. The interface has only static and final variables. Implementation: Abstract class can provide the implementation of the interface. Interface can't provide the implementation of an abstract class.
Unlike concrete classes, they merely specify an interface to an object, not an object itself. All you can do with an abstract type is to declare a variable to be of that type. Such a variable can point to any actual object which is a subtype of that abstract class.
The code is fine, the final variable is initialized in the constructor of FooType
.
You cannot instantiate FooType
because of it being abstract. But if you create a non abstract subclass of FooType
, the constructor will be called.
If you do not have an explicit call to super(...)
in a constructor, the Java Compiler will add it automatically. Therefore it is ensured that a constructor of every class in the inheritance chain is called.
You can have constructors, methods, properties, everything in abstract classes that you can have in non-abstract classes as well. You just can't instantiate the class. So there is nothing wrong with this code.
In a deriving class you can call the constructor and set the final property:
public class Foo extends FooType
{
public Foo()
{
super(); // <-- Call constructor of FooType
}
}
if you don't specify a call to super(), it will be inserted anyway by the compiler.
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