dpcasady
dpcasady

Reputation: 1846

Accessing parent class property set by child class

I'm trying to access a property from a method in a parent class where that property is initialized in a child class like so:

abstract class Parent {
    String description
    String name

    def printDescription() {
        println "description: ${description}"
    }
}

class Child extends Parent {
    String description = "child description"
}

Child child = new Child(name: 'Mark')
child.printDescription()                       // prints "description: null"

When the method is executed however, the description property is null. I need to pass the child's description back up to the parent constructor. What is the best way to do that while maintaining grails' auto-generated map constructors? Thanks!

EDIT:

Adding an empty constructor does actually work for what I'm looking for. The constructor is still called when using grails dynamic map constructor, e.g. Child child = new Child(name: 'Mark').

Child() {
    this.description = "child description"
}

Upvotes: 1

Views: 1846

Answers (1)

MiiinimalLogic
MiiinimalLogic

Reputation: 818

You're setting the description variable of the child class but trying to access the description variable of the parent class, which was never set.

Upvotes: 1

Related Questions