Home > Back-end >  Can I create abstract properties in Java?
Can I create abstract properties in Java?

Time:07-12

Is this code legal in Java? I'm trying to build an abstract cards class and a sub class that will inherit methods and properties from the abstract class. I know I can create abstract methods and regular methods too, but can I also create properties in the abreact class?

public abstract class CardsDecks {

    private static String hearts = "HEARTS";
    private static String clubs = "CLUBS";
    private static String diamonds = "DIAMOND";
    private static String spades = "SPADES";

    abstract String shuffle();
}

CodePudding user response:

Yes you can (see above)... but ...

What you have there should (probably) not be described as properties or model like that.

They should be modeled constants ... unless it is a clear requirement that you should be able to change the names of the card suites at runtime! Declare them as static final, not just static.

Why? Because you don't want some code accidentally assigning to one of those "properties". And someone reading the code doesn't want to have to scan the code base looking for accidental assignments.

I also think it is (ultimately) unhelpful to describe them as simply properties, even if they are not constant. I would call them "class properties" to distinguish them from ordinary (not static) "properties". (But this is my opinion ...)

And finally, mutable static fields are in general a bad idea. They are antithetic to OO, and introduce a bunch of problems; e.g. they are potentially problematic when you are writing unit tests.


It is also worth noting that fields declared as static in Java are not inherited (in the full sense) and cannot be overridden.

CodePudding user response:

Yes, abstract classes can have properties.

An abstract class is much like a regular class, except that they cannot be instantiated. They must be implemented/extended by a subclass, this includes the abstract methods within them.

CodePudding user response:

No, you can't create properties in an abstract class. You have to create properties in a subclass or another class that you will inherit to use your abstract class.

  • Related