Search code examples
javaconstructorencapsulationnaming

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.

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'}