0

I am making a cricket tournament management system. I has a class named Player and two child classes Batsman and Bowler. The Player class has following data members:

private String name;
private int ID;
private int age;
private int height;

now Batsman class has Batsman specific members and Bowler class has some Bowler specific members.

I have an abstract addRecord method in Player class which is implemented in both Batsman and Player class. I want the to use a common file for both child classes in such a way that ID is not duplicated in the file.
And then I can retrieve only Batsman's or only Bowler's records from file as needed and make an array of Batsman or Bowler objects from them.

Is there a way to use Class.forName() and then created an instance of that class by dynamically at runtime using a string containing the class name.

Please help!

cstayyab
  • 318
  • 2
  • 20
  • I'm not entirely sure what you're asking, but you can use instanceof to check if the object is a batsman or bowler after it has been created. – arkdevelopment Dec 29 '17 at 04:49
  • Write a separate class to provide unique IDs for both `Batsman` and `Bowler` objects. – Jude Niroshan Dec 29 '17 at 04:53
  • I would suggest you to use a Database for that and not a file. - You cant read only some 'records' from a file, because it is not indexed – fab Dec 29 '17 at 05:07
  • @fab i need to use file i want to read the whole line from file and then use split() to get ID and other fields. And also it is a requirement of my Assignment to use File and not the database. – cstayyab Dec 29 '17 at 05:22
  • @MuhammadTayyabSheikh could you pleas make an example, how the objects and the file should look like? – fab Dec 29 '17 at 05:26
  • @fab here is the format of file: ID|name|age|height|type of player(class name in my case)|whatever|else – cstayyab Dec 29 '17 at 05:28

1 Answers1

-1

This could be a start for you:

public class IdCounter {

    private static Integer nextId;

    static int getNextId(){
        if (nextId == null){
            //read file and get highest ID
        }
        return nextId++;
    }
}


public class addRecord {

    private String name;
    private int ID;
    private int age;
    private int height;

    private void saveRecord(){
        if(ID==0){
            ID = IdCounter.getNextId();
        }
    }
}

If you working with an UI you may need a thread save solution, with locking... http://winterbe.com/posts/2015/04/30/java8-concurrency-tutorial-synchronized-locks-examples/

fab
  • 1,189
  • 12
  • 21
  • How does it answer the question? Question was "Is there a way to use Class.forName() and then created an instance of that class by dynamically at runtime using a string containing the class name." – talex Aug 14 '20 at 06:28
  • @talex the initial question was not asking "Is there a way to use Class.forName()..." ;) https://stackoverflow.com/posts/48017467/revisions – fab Aug 14 '20 at 10:22