2

I build a class with the constructor:

public Door(String name){

  this.name = name;
 }

Is there a way where I can create a default constructor where the name becomes whatever the user assigns this object. For example:

{

  Door blackDoor = new Door();
}

Would make the

blackDoor.name = blackDoor?

Hamza Khan
  • 131
  • 10
  • 2
    Nope. Sorry. Unless... No, forget it. – ZhongYu May 23 '15 at 22:58
  • 1
    The obvious question is: why would you need this? – biziclop May 23 '15 at 23:04
  • 1
    This is possible through reflection, but only while debugging. See [this question](https://stackoverflow.com/questions/14459674/how-to-get-variable-name-in-java) for example. **Don't use this in production builds. Names can change and variables might be removed due to compiler optimizations.** – GiantTree May 23 '15 at 23:06
  • @GiantTree thanks a lot. I was just curious to know if it could be done. – Hamza Khan May 23 '15 at 23:13

1 Answers1

0
public class Bleh {

    public static void main(String[] args) {
        BlackDoor bd = new BlackDoor();
        System.out.println(bd.name);
    }
}

class Door {
    String name;
    public Door(){
        this.name = this.getClass().getName();
    }
}


class BlackDoor extends Door{
}
Monish Sen
  • 1,773
  • 3
  • 20
  • 32