2013年10月7日星期一

java set and get

I used to get and do not get the program to run , but what difference does it make ?

package book_two.com.demo;

import book_two.com.bean.Rectangle;
public class RectangleDemo {

public static void main (String [] agrs)
{
Rectangle rect = new Rectangle ();
/ / rect.length = 12.36; / / do not allow external calls
/ / rect.width = 11.36;
/ / System.out.println (" area of ​​the rectangle is :" + rect.area ());
rect.setWidth (12.36);
rect.setLength (16.56); / / call private methods
rect.display ();
}
}



package book_two.com.bean;

public class Rectangle {

private double length;
private double width;
/ / public double length;
/ / public double width;

public void setWidth (double w)
{
width = w;
}
/ * public double getWidth ()
{
return width;
} * /
public void setLength (double l)
{
length = l;
}
/ * public double getLength ()
{
return length;
} * /
double area ()
{
return length * width;
}
public void display ()
{
System.out.println (" length :" + length + "\ t width :" + width);
System.out.println (" area of ​​the rectangle is :" + area ());
}
}
------ Solution ----------------------------------- ---------
this is the package
using the set methods to attribute assignment , so that your incoming data can be set in this way in the verification and validation ( of course, most of the time we see are a direct assignment ) , the advantage lies in the field of packaging
hidden parts (private) is a class that should not be disclosed to your part.
For example :
you save money through an ATM at the bank when you need to pass some operations atm machine to paper money, counting money is . Without these , you just entered, enter 10 million, the result did not really save you so much money he can not control it.
------ For reference only -------------------------------------- -
private double length;
private double width;


not write public access to the get method in the external value of less than a length and width
------ For reference only ------------------ ---------------------
method can be used to protect private property .

example you here, if I ask a rectangular length must be bigger than the width can be set in two ways in the limit , and if exposed to go directly to the property , you can not achieve this goal .
------ For reference only -------------------------------------- -
nice answer , understand, thank you.

没有评论:

发表评论