Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Creating class name generator in java

I am having quite a bit of problems naming variable automatically in java.

The problem in question :

I am making a class Point (different from java.awt.Point). It has an attribute this.name. From a testPoint.java I just create a Point and print its name.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

To create a Point I have two linked constructor :

public Point() {
        this("AutoName");
    }

public Point(String name) {
        this.name = name;
    }

If a name is given in the testPoint.java, the point will be named according to that name. If no name is given the Point will be named AutoName.

What i want is that if no name is given the first no named Point gets AutoName1 as a name, the second AutoName2 etc.

Is there a way to do that without introducing new classes ? It would be easy if I can create a global variable in java like in C and Python but I think that does not respect the encapsulation principle…

>Solution :

Use a static int in the class to hold the number of instanciation


class Point {
    static int creationCount = 1;
    String name;

    public Point() {
        this("AutoName" + (creationCount++));
    }

    public Point(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Point{name='" + name + "'}";
    }
}
System.out.println(new Point());       // Point{name='AutoName1'}
System.out.println(new Point("abc"));  // Point{name='abc'}
System.out.println(new Point());       // Point{name='AutoName2'}
System.out.println(new Point("bcd"));  // Point{name='bcd'}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading