简体   繁体   中英

Can a variable be abstract in an abstract Java class?

Can you declare an abstract variable type in an abstract class? I am receiving an error when I put this line of code in. I can declare a variable that is final and not final but I am not sure if I should be able to declare a variable that is abstract. What would be the real advantage between an interface and an abstract class?

  Error Code:

       abstract int myScore = 100; <-- Causes an error

Code:

public abstract class GraphicObject {
       int home = 100;
       String myString = "";
       final int score = 0;

       abstract void draw();
       abstract void meMethod1();
       abstract void meMethod2();

       int meMethod3() {
           return 0;
       }
    }

"Can you declare an abstract variable type in an abstract class?"

No, according to the JLS ( http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.3.1 ).

Why should it be abstract if you can't implement variables? Abstract methods only mean that they must be implemented further in your code (by a class that extends that abstract class). For variable that won't make any since they keep being the same type. myscore will always be an int.

You may be tinking about override the value of myscore by the class that extends that abstract class.

An abstract method is a method that doesn't have a body. This is because it's meant to be overridden in all concrete (non-abstract) subclasses and, thanks to polymorphism, the abstract stub can never be invoked.

Given the above, and since there is no polymorphism for fields (or a way to override fields at all), an abstract field would be meaningless.

If what you want to do is have a field whose default value is different for every subclass, then you can assign its default value in the constructor(s) of each class. You don't need to make it abstract in order to do this.

No, abstract is used so that methods can only be implemented in subclasses. See http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html

You cannot declare an abstract variable in Java.

If you wish to declare a variable in a super-class, which must be set by its sub-classes, you can define an abstract method to set that value...

For example:

public abstract class Foo {

    Object obj;

    public Foo() {
        init();
    }

    protected void init() {
        obj = getObjInitVal();
    }

    abstract protected Object getObjInitVal();

}


public class Bar extends Foo {

    @Override
    protected Object getObjInitVal() {
        return new Object();
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM