OnJava8-Examples/staticchecking/drc/DogAndRobotCollections.java

36 lines
891 B
Java
Raw Normal View History

2015-05-18 23:05:20 -07:00
//: staticchecking/drc/DogAndRobotCollections.java
2015-05-29 14:18:51 -07:00
// <20>2015 MindView LLC: see Copyright.txt
2015-05-18 23:05:20 -07:00
package staticchecking.drc;
import java.util.*;
class Dog {
public void talk() {
System.out.println("Woof!");
}
public void reproduce() { }
}
class Robot {
public void talk() {
System.out.println("Click!");
}
public void oilChange() { }
}
public class DogAndRobotCollections {
public static void main(String[] args) {
2015-05-27 23:30:19 -07:00
List<Dog> dogList = new ArrayList<>();
List<Robot> robotList = new ArrayList<>();
2015-05-18 23:05:20 -07:00
for(int i = 0; i < 10; i++)
dogList.add(new Dog());
// dogList.add(new Robot()); // Compile-time error
for(int i = 0; i < 10; i++)
robotList.add(new Robot());
// robotList.add(new Dog()); // Compile-time error
2015-05-27 23:30:19 -07:00
// No cast necessary
dogList.forEach(Dog::talk);
// No cast necessary
robotList.forEach(Robot::talk);
2015-05-18 23:05:20 -07:00
}
} ///:~