I have the following example:
package cage;
import java.util.HashSet;
import java.util.Set;
import animals.Animal;
public class Cage<T extends Animal> { //A cage for some types of animals
private Set<T> set = new HashSet<T>();
public void add(T animal) {
set.add(animal);
}
public void showAnimals() {
for (T animal : set) {
System.out.println(animal.getName());
}
}
public void transferTo(Cage<? super T> cage) {
cage.set.addAll(this.set);
}
}
Main class:
package exe;
import cage.Cage;
import animals.Animal;
import animals.Ape;
import animals.Lion;
import animals.Rat;
public class Main {
public static void main(String[] args) {
System.out.println("Test with super........");
Cage<Animal> animals = new Cage<Animal>();
Cage<Lion> lions = new Cage<Lion>();
animals.add(new Rat(true, 4, "Rat", true)); // OK to put a Rat into a Cage<Animal>
lions.add(new Lion(true, 4, "King", 9));
lions.transferTo(animals); // invoke the super generic method -> animals is SUPER of lion.
animals.showAnimals();
}
}
In the class cage there is an invocation
cage.set.addAll(this.set);
Why does it work to invoke “cage.set…” with the dot notation althought I have neither a getSet-method nor is “set” static? What’s the technical background?
You’re just using field access. Having a
getSet()method would make no difference, as the Java compiler won’t use an accessor method automatically for you.I suspect what you’re missing is that
privateaccess isn’t determined by the object whose member you’re trying to access – the code inCagehas access to the private members of any otherCage, including thesetfield.Section 6.6 of the Java Language Specification describes access control, including: