Class Person public Person String n Date d name n birthda

Class Person

{

            public Person (String n, Date d)

            {

                        name = n;

                        birthday = d;

            }

            public String getName() { return name;}

            public Date getBirthDay() { return birthDay; }

            private String name;

            private Date birthDay;

}

A. Based on the Person class, Discuss how does the following code break Java’s encapsulation?

Person mike = new Person (“Mike”, new Date (92,1,10);

. . .

. . .

Date d = mike.getBirthDay();

d.setTime(1000);

B. What changes would you make to the previous code into avoid having this problem. Justify your answer

Solution

In given class the constructor declared is public which can break encapsulation. So we can instead change the access specifier of the contructor to defaut.We can also declare the setter methods to set the values of the variables.


Class Person

{

            Person (String n, Date d)

            {

                        name = n;

                        birthday = d;

            }

            public String getName() { return name;}

            public Date getBirthDay() { return birthDay; }
  
            public String setName(String name)   { }

            public String setBirthDay(Date birthDay)   { }

            private String name;

            private Date birthDay;

}

Class Person { public Person (String n, Date d) { name = n; birthday = d; } public String getName() { return name;} public Date getBirthDay() { return birthDay;
Class Person { public Person (String n, Date d) { name = n; birthday = d; } public String getName() { return name;} public Date getBirthDay() { return birthDay;

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site