'
4-5 .
, ' , int, double, char. , . , . ' . (class ).
, ( object) . , (attribute) (method). , , ( int, ) . . , , . . , .
, . , , , .
, . (constructor).
:
public class Example //
{
Attributes
Constructors . ( )
Methods ( )
}
, .
: Bucket. double, _capacity currentAmount_. ( ) , , , , , . fill , , ( ).
main ( , 1-2). :
:
Bucket buck = new Bucket(3.2,1.1); // . .
System.out.println(buck._capacity); // . 3.2
buck.fill(2); // .
System.out.println(buck._currentAmount); // . 3.1
buck.fill(1); // .
System.out.println(buck._currentAmount); // 3.2, .
, , . . ( ), , , , .
, "" . (access modifier). .
, . , . , . . Bucket : ( 1-2, , )
Bucket(double capacity, double amountToFill) ,
:
void fill(double amountToFill) .
double getCapacity()
double getCurrentAmount()
void setCapacity(double newCapacity)
void pourInto(Bucket bucketInto) , .
, '
public String toString()
( public , )
, . ( , , ). ,
:
System.out.println(buck.toString())
:
System.out.println(buck)
toString . toString, , toString , , .
. .
:
:
public class Bucket
{
}
_capacity, _currentAmount, double. :
:
public class Bucket
{
private double _capacity, _currentAmount; // .
}
:
public Bucket(double capacity, double currentAmount)
{
_capacity = capacity;
_currentAmount = currentAmount;
{
,
.
_ . capacity currentAmount, , capacity , capacity. . capacity currentAmount. , .
, public
:
buck.capacity = capacity;
, capacity buck, capacity .
, . ' this. this, , . , :
:
public Bucket(double capacity, double currentAmount)
{
this.capacity = capacity;
this.currentAmount = currentAmount;
}
:
public void fill(double amountToFill)
{
double possibleAmount = _currentAmount + amountToFill;
_currentAmount = Math.min(_capacity, possibleAmount); // , :
if(possibleAmount > _capacity)
_currentAmount = _capacity;
else
_currentAmount = possibleAmount;
}
, if for, , { - }. toString:
:
public String toString()
{
return The capacity is: + _capacity + and the current amount is: + _currentAmount;
}
:
:
public class Bucket
{
private double _capacity, _currentAmount;
public Bucket(double capacity, double currentAmount){}
public void fill(double amountToFill){}
public double getCapacity(){..}
public double getCurrentAmount(){}
public void setCapacity(double newCapacity){}
public void pourInto(Bucket bucketInto) {}
public String toString() {}
... .
}
:
Bucket buck1 = new Bucket(3.3, 1.3);
Bucket buck2 = new Bucket(7.5, 6);
buck2.setCapacity(10);
buck1.fill(2);
buck1.pourInto(buck2);
System.out.println(buck1);
System.out.println(buck2);
:
The capacity is 3.3 and the current amount is 0
The capacity is 10 and the current amount is 9.3
( )
Point x-y. , x y. get set Bucket: get , set . move , ( ). toString (x,y).
.
.
, Bucket " '"
, .
.