-1

I would like to add method through my constructor and use it after :

RegularAxis lon = new RegularAxis(){
    public String returnHello(){
         return "hello";
    }
};

lon.returnHello();

I cannot access my new method. is there an other way?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Fab83i
  • 85
  • 7
  • That's not how Java works, why do you want to do this instead of defining the method in the normal way? – UnholySheep Aug 31 '22 at 08:05
  • 1
    The method has to be added in the class declaration, or via a setter which takes a function argument or something similar, like a lambda – SimonC Aug 31 '22 at 08:05
  • Because my regularAxis is part of a library, I cannot edit it. And i would like a custom method – Fab83i Aug 31 '22 at 08:06
  • 2
    In your example, you are creating anonymous subclass. You can: 1) use var to infer the type of the variable. Thus the `lon` variable has more precise type, giving you access to the new method. 2) Use regular subclass if you want to pass this variable somewhere, preserving its type. – Lesiak Aug 31 '22 at 08:08
  • are you referring to something like [this](https://stackoverflow.com/a/1958961/16034206)? – experiment unit 1998X Aug 31 '22 at 08:10
  • 1
    FYI: This is not a "constructor function" (that term doesn't exist in Java), you're creating an anonymous subclass. – Mark Rotteveel Aug 31 '22 at 08:15

1 Answers1

5

You can call it as part of the same statement:

new RegularAxis(){
    public String returnHello(){
         return "hello";
    }
}.returnHello();

Or you can capture the anonymous type with a var variable in Java 10+ (thanks @Lesiak):

var lon = new RegularAxis(){
    public String returnHello(){
         return "hello";
    }
};

lon.returnHello();

Otherwise, you'll have to declare it as a proper class:

class IrregularAxis extends RegularAxis {
    public String returnHello(){
         return "hello";
    }
}

IrregularAxis lon = new IrregularAxis();
lon.returnHello();
shmosel
  • 49,289
  • 6
  • 73
  • 138