1. Define a class Cat in which each object has a name and a weight. Do not forget to include a constructor, accessor methods, and mutator methods.
2. In the main method,
Solution:
public class Cat{
private String name;
private double weight;
public Cat(String aname, double aweight)
{name = aname; weight = aweight;}
public String getName(){return name;}
public double getWeight(){return weight;}
public void setName(String newName){name = newName;}
public void setWeight(double newWeight){weight = newWeight;}
}
in the main program:
Cat[] cats = new Cat[2];
cats[0] = new Cat("Fluffy", 3.0);
cats[1] = new Cat("Tiny", 1.2);
double average = (cats[0].getweight() + cats[1].getweight()) / 2.0;
System.out.println(average);
tracing:
First, we define a new array cats of objects of type Point:
----
| \| cats
---\
\
\|
- -------
| nil | cats[0]
-------
| nil | cats[1]
-------
We then call a constructor method:
--------------
| ---------- |
| | Fluffy | |
| ---------- |
| aname |
| ---------- |
| | 3.0 | |
| ---------- |
| aweight |
--------------
| |
| |
| |
| |
| |
| |
--------------
Cat
after which we create a new object:
--------------
| ---------- |
| | Fluffy | |
| ---------- |
| name |
| ---------- |
| | 3.0 | |
| ---------- |
| weight |
--------------
cats[0]
We then call a constructor method:
--------------
| ---------- |
| | Tiny | |
| ---------- |
| aname |
| ---------- |
| | 1.2 | |
| ---------- |
| aweight |
--------------
| |
| |
| |
| |
| |
| |
--------------
Cat
after which we create a new object:
--------------
| ---------- |
| | Tiny | |
| ---------- |
| name |
| ---------- |
| | 3.0 | |
| ---------- |
| weight |
--------------
cats[1]
Then, we define a new variable average and assign to it the value
(3.0 + 1.2) / 2.0 = 4.2 / 2.0 = 2.1 and print this value 2.1