java 实例分析 接口与类的应用

来源:互联网 发布:变更ip地址软件 编辑:程序博客网 时间:2024/06/10 19:55
  1 import java.util.Scanner;
2
3 interface Pet{
4 public int getAge();
5 public String getColor();
6 public String getName();
7 }
8
9 class Cat implements Pet{
10 private String name;
11 private String color;
12 private int age;
13 public Cat(String name,String color,int age){
14 this.setName(name);
15 this.setColor(color);
16 this.setAge(age);
17 }
18 public int getAge() {
19 return age;
20 }
21 public String getColor() {
22 return color;
23 }
24 public String getName(){
25 return this.name;
26 }
27 public void setAge(int age) {
28 this.age = age;
29 }
30 public void setColor(String color) {
31 this.color = color;
32 }
33 public void setName(String name) {
34 this.name = name;
35 }
36
37 }
38
39 class Dog implements Pet{
40 private String name;
41 private String color;
42 private int age;
43 public Dog(String name,String color,int age){
44 this.setName(name);
45 this.setColor(color);
46 this.setAge(age);
47 }
48 public int getAge() {
49 return age;
50 }
51 public String getColor() {
52 return color;
53 }
54 public String getName(){
55 return this.name;
56 }
57 public void setAge(int age) {
58 this.age = age;
59 }
60 public void setColor(String color) {
61 this.color = color;
62 }
63 public void setName(String name) {
64 this.name = name;
65 }
66
67 }
68 class PetShop{
69 private Pet[] pets;
70 private int foot;
71 public PetShop(int len){
72 if(len>0){
73 this.pets=new Pet[len];
74 }
75 else{
76 this.pets=new Pet[1];
77 }
78 }
79
80 public boolean add(Pet pet){
81 if(this.foot<this.pets.length){
82 this.pets[this.foot]=pet;
83 this.foot++;
84 return true;
85 }
86 else{
87 return false;
88 }
89 }
90
91 public Pet[] search(String keyWord){//关键字查找,返回的是Pet数组
92 Pet p[]=null;
93 int count=0;
94 for(int i=0;i<this.pets.length;i++){
95 if(this.pets[i]!=null){
96 if(this.pets[i].getName().indexOf(keyWord)!=-1||this.pets[i].getColor().indexOf(keyWord)!=-1){
97 count++;
98 }
99 }
100 }
101 p=new Pet[count];//开辟对象数组
102 int f=0;//设置增加的标记
103 for(int i=0;i<this.pets.length;i++){
104 if(this.pets[i]!=null){
105 if(this.pets[i].getName().indexOf(keyWord)!=-1||this.pets[i].getColor().indexOf(keyWord)!=-1){
106 p[f]=this.pets[i];
107 f++;
108 }
109 }
110 }
111 return p;
112 }
113 }
114 public class PetshopDemo {
115
116 public static void main(String args[]){
117 PetShop ps=new PetShop(2);
118 ps.add(new Cat("whiteCat","white",2));
119 ps.add(new Dog("blackDog","black",3));
120 print(ps.search("black"));
121 }
122 public static void print(Pet p[]){
123 for(int i=0;i<p.length;i++){
124 if(p[i]!=null){
125 System.out.println(p[i].getName()+","+p[i].getColor()+","+p[i].getAge());
126 }
127 }
128 }
129 }

-------------------------------------------------------------------------------------------------------------------------------------------------

运用pet接口,自定义宠物的数量,应使用数组。运用indexOf统计数量