Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Final variables in abstract classes

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;
    }
}
like image 859
imacake Avatar asked Jul 02 '11 15:07

imacake


People also ask

Can abstract class have final variables?

3) Abstract class can have final, non-final, static and non-static variables. Interface has only static and final variables.

Can we define final in abstract class?

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.

Can abstract class have non-final variables?

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.

Can I declare variable in 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.


2 Answers

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.

like image 73
Hendrik Brummermann Avatar answered Sep 24 '22 08:09

Hendrik Brummermann


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.

like image 40
yankee Avatar answered Sep 24 '22 08:09

yankee