Ylen hn lig charaterisis 1. The name property which is accessible by other objec
ID: 3721117 • Letter: Y
Question
Ylen hn lig charaterisis 1. The name property which is accessible by other objects of this prototype. 2. The password property which canrot be accessed by other objects of this prolotype. 3. The counter property whose value is shared among all cbjects of this prototype. You need to create two objects of this prototype in order to do the following tasks: 1. Show how to access the name property in both objects. 2. What output do you get if you try to access the password property? How can you correct it? How to access the counter property? If you change the value of the counter propery in one object, does it affect the property value on the second object?Explanation / Answer
PERSON PROTOTYPE ( CLASS):
class Person{
public String name;
private String password;
public static int counter = 0 ;
public Person()
{
counter=counter+1;
name = null;
password = null;
}
public Person(String s)
{
counter=counter+1;
name= s;
password=null;
}
public Person(String n, String p)
{
counter=counter+1;
name=n;
password=p;
}
public void setPassword(String s)
{
this.password=s;
}
public String getPassword()
{
return this.password;
}
// FUNCTION TO ACCESS NAME OF OTHETR OBJECT
public String getName(Person p)
{
return p.name;
}
// FUCTION TO ACCESS NAME OF SAME OBJECT
public String getName()
{
return this.name;
}
}
1)
class TestClass {
public static void main(String args[] ) throws Exception {
Person p1 = new Person("alice","abc");
Person p2 = new Person("Bob","def");
// ACCESS NAME OF BOTH OBJECTS BY SELF
System.out.println(p1.name);
System.out.println(p2.name);
}
}
Output:
2)
The program will give access error if you try to access password property. To correct it we have to write a method in prototype to access the password property
public String getPassword()
{
return this.password;
}
class TestClass {
public static void main(String args[] ) throws Exception {
// create two objects p1 and p2 with name and password
Person p1 = new Person("alice","abc");
Person p2 = new Person("Bob","def");
// TRYING TO ACCESS PASSWORD PROPERTY
System.out.println(p1.getPassword());
System.out.println(p2.getPassword());
}
}
Output:
3)
class TestClass {
public static void main(String args[] ) throws Exception {
// create two objects p1 and p2 with name and password
Person p1 = new Person("alice","abc");
Person p2 = new Person("Bob","def");
// TRYING TO ACCESS COUNTER PROPERTY
System.out.println(p1.counter);
System.out.println(p2.counter);
//CHANGE THE COUNTER OF P1
p1.counter = 20;
// since wer have implimented counter to be shared among all objects
//if we change counter of p1, it will reflect in p2 also
System.out.println(p2.counter);
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.