Can you Explain what each line is word for word and what it will do? What is the
ID: 3836948 • Letter: C
Question
Can you Explain what each line is word for word and what it will do?
What is the definition of set and get and how do I understand how this code specifically works?
class Person
{
public string LastName { set; get; }
public int Hairs { set; get; }
public Person() { } // default constructor
public Person(string nm, int hr)
{
LastName = nm; Hairs = hr;
}
public string ToString() // default system method
{
return "The class is a Person class. The last name is "+LastName + ", hairs are " + String.Format("{0:N0}",Hairs);
}
public string Msg() // method
{
return String.Format("{0:N0}",Hairs)+ " is wonderful!!";
Explanation / Answer
public class Person {//Person is the name of the class always we should follow PascalCaps ie ever first letter of the word should start with capital letter
private String lastName;//we should take this member variables as private so that the visibility is inside the class
private int hairs;
public String getLastName() {//as lastName is private we cannot access out side the class so in order to access it we use thid getter method
return lastName;
}
public void setLastName(String lastName) {//this is setter method used to set values
this.lastName = lastName;//this keyword is used to say that objects
}
public int getHairs() {
return hairs;
}
public void setHairs(int hairs) {
this.hairs = hairs;
}
public Person()//this is the default constructor used to assign default values to member variables when an object is created
{
lastName=null;//for String data type default value is null
hairs=0;//for integer data type default value is 0
}
public Person(String nm,int hr)//this is parameterized constructor used to initialize membered variables with the given values at the time of object creation
{
lastName=nm;//lastName is assigned with value present in nm
hairs=hr;//hairs is assigned with value present in hr
}
@Override
public String toString() {//this method is used to display all the members variables of this class
return "Person [lastName=" + lastName + ", hairs=" + hairs + "]";
}
public String Msg()
{
return String.format("Hi %s",hairs)+" is wonderful!!!";//the value present in hairs is replaced with %s
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.