Get GirlName using setName and getName
This code will require two classes. One is papaya and the other one mango.
public class papaya {
private String girlName;
papaya(){
setName("MJ");
}
public void setName(String girlName) {
this.girlName = girlName;
}
public String getName() {
return this.girlName;
}
public void printDetails() {
System.out.printf("The name of your girl is %s", getName());
}
}
Now let us see class mango which is our main class.
class mango {
public static void main (String[] args) {
papaya papayaObject = new papaya();
papayaObject.setName("AJ");
papayaObject.printDetails();
}
}
OUTPUT
Now let us see the code in mango class when we are not giving name as an input to the method.
So, constructor will initialise the value this time.
class mango {
public static void main (String[] args) {
papaya papayaObject = new papaya();
papayaObject.printDetails();
}
}
OUTPUT
NOTES:
- in getter we don't use any parameter in the parenthesis. And always return the datatype and also make sure that we are returning the variable of main class that is private here.
- In printDetails we can also use return type and then print the value in mango class and at the same time you can print it in same class and then just call the method printDetails in the main class using the object papayaObject.
- We also use the constructor for initialising the value.
In constructor just give the respecting parameters in the parenthesis and then just call the method setter inside and give the available parameter. This is also the concept of constructor overloading.
Comments
Post a Comment