'Is it possible that getters and setters be made abstract in an abstract?

public abstract class Modeller {
    private String model;
     abstract void getModel();
    abstract void setModel(String model);

Is it possible having something like this. If so how well is it implemented because what code snippet I have above runs with errors.



Solution 1:[1]

tl;dr

Your code violates the rule that abstract methods have no body.

Details

An abstract class in Java can have:

  • Methods that are concrete (implemented).
  • Methods that are abstract (not implemented).

Another class extending that abstract class:

  • May override the concrete methods
  • Must implement the abstract methods.

Your example code is not proper Java code because you have abstract methods that carry an implementation. By definition, an abstract method has no implementation.

Side issue: Your getter method must return something, but you declared it void.

Side issue: A private member field is not visible to subclass. So change that scope if you want abstract methods.

(By the way, single l in "modeler")

Modify your code to either be this:

public abstract class Modeler {
    // Fields
    String model;

    // Methods
    abstract String getModel() ;
    abstract void setModel( String model ) ;
}

(See a working example of this at IdeOne.com)

… or this:

public abstract class Modeler {
    // Fields
    private String model;

    // Methods
    String getModel(){
        return this.model;
    }
    void setModel( String model ){
        this.model = model;
    }
}

See a working example of this code at IdeOne.com.


I have ignored the issue of whether or not this is smart handling of getter/setter accessor methods. I want to focus on your specific question of how to do abstract methods.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1