Reputation: 1254
public class Horse extends Animal {
private Halter myHalter = new Halter();
public void tie(LeadRope rope) {
myHalter.tie(rope); // Delegate tie behavior to the
// Halter object
}
}
public class Halter {
public void tie(LeadRope aRope) {
// Do the actual tie work here
}
}
In this example Horse has-a Halter.Can we call myHalter.tie(rope); like this:
public class Horse extends Animal {
private Halter myHalter = new Halter();
myHalter.tie(rope); // Without using the public void tie method
}
It gives an error. My explanation to this is that its not a main() method but could anyone explain it in a better way.
Upvotes: 0
Views: 896
Reputation: 25950
Statements other than variable/field declarations in a class body must be put into a method body, a constructor or an initializer block. For example, it would be OK if you attempt to compile this code:
public class Horse {
private Halter myHalter = new Halter();
{
myHalter.tie(new LeadRope());
}
}
Upvotes: 1
Reputation: 33534
Ok try this....
- Has-A relationship
is known as Composition
.
public class Bathroom{
Tub tub;
}
public class Tub{
}
- We can say that Bathroom
has a reference of type Tub
, that means Bathroom
has an instance variable of type tub
.
Upvotes: 1
Reputation: 810
You cant call method in class block , you have to create a method and than you can call a method in the body of a method, or you can call a method in static, instance or constructor block
Upvotes: 1