implementing concatenation of attributes into a instant variables while writing a constructor

I'm creating a constructor to initialize my instance variables.

An instance variable id should be concatenation of three attributes id + memberId + borrowDate.

How do I implement a concatenation of three attributes into an id instance variable in the constructor?

1 answer

  • answered 2018-05-16 06:52 prms

    //Main.java

    import java.util.Date;
    
    public class Main {
        public static void main(String[] args) {
            Person p = new Person(1, 12, new Date());
    
            System.out.println(p.getId());
    
    
        }
    
    
    }
    

    //Person.java

    import java.util.Date;
    
    public class Person{
        private String id;
    
        public Person(int attrId, int id, Date borrowDate){
            this.id = String.valueOf(attrId) + String.valueOf(id) + String.valueOf(borrowDate);
        }
    
        public String getId(){
            return id;
        }
    }
    

    This uses a parameterized constructor to accept values. Those parameters are then concatenated and new value is assigned to private field. I've used default Date format. You can parse it according to the format required.