OnJava8-Examples/staticchecking/drc/DogAndRobotCollections.java

60 lines
1.1 KiB
Java
Raw Normal View History

2015-09-07 11:44:36 -06:00
// staticchecking/drc/DogAndRobotCollections.java
2015-11-14 16:18:05 -08:00
// <20>2016 MindView LLC: see Copyright.txt
2015-11-15 15:51:35 -08:00
// We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
2015-06-15 17:47:35 -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) {
List<Dog> dogList = new ArrayList<>();
List<Robot> robotList = new ArrayList<>();
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
// No cast necessary
dogList.forEach(Dog::talk);
// No cast necessary
robotList.forEach(Robot::talk);
}
2015-09-07 11:44:36 -06:00
}
/* Output:
2015-06-15 17:47:35 -07:00
Woof!
Woof!
Woof!
Woof!
Woof!
Woof!
Woof!
Woof!
Woof!
Woof!
Click!
Click!
Click!
Click!
Click!
Click!
Click!
Click!
Click!
Click!
2015-09-07 11:44:36 -06:00
*/