Java--类/接口作为成员变量
成员变量也可以使用自定义的类
如何使用String就如何使用自定义的类
代码示例
Weapon类
public class Weapon {
private String code;
public Weapon(String code) {
this.code = code;
}
public Weapon() {
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
}
Hero类
public class Hero {
private String name;
private int age;
private Weapon weapon;
public Hero(String name, int age, Weapon weapon) {
this.name = name;
this.age = age;
this.weapon = weapon;
}
public Hero() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Weapon getWeapon() {
return weapon;
}
public void setWeapon(Weapon weapon) {
this.weapon = weapon;
}
public void attack()
{
System.out.println("年龄为"+age+"的"+name+"正在使用"+weapon.getCode()+"攻击敌方");
}
}
Main方法
public class Main {
public static void main(String[] args) {
Hero one = new Hero();
//为英雄设置名称
one.setName("奥摩");
one.setAge(20);
Weapon two= new Weapon("AWM");
one.setWeapon(two);//装备武器
one.attack();//攻击
}
}
接口作为成员变量
将接口作为成员变量
接口的实现
-
使用单独的定义类
-
使用匿名内部类
-
同时使用匿名内部类和匿名对象
代码实现
Hero类
public class Hero { private String name; private Skll skll; public Hero() { } public void attack() { System.out.println("我是"+name+"正在释放技能"); skll.show(); System.out.println("技能释放完毕"); } public Hero(String name, Skll skll) { this.name = name; this.skll = skll; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Skll getSkll() { return skll; } public void setSkll(Skll skll) { this.skll = skll; } }
Skll接口实现类
public class NewSkll implements Skll{
@Override
public void show() {
System.out.println("突突突");
}
}
Main方法
public class Main {
public static void main(String[] args) {
Hero one = new Hero();
one.setName("奥摩");
// Skll skll= new NewSkll();//使用接口实现类
// Skll skll =new Skll() {//使用匿名内部类
// @Override
// public void show() {
// System.out.println("突突突突突");
// }
// };
one.setSkll(new Skll() {
@Override
public void show() {
System.out.println("突突突突突");
}
});
one.attack();
}
}
接口作为方法参数和返回值
接口也是可以作为返回值和方法参数的
代码示例
package Demo01;
import java.util.ArrayList;
import java.util.List;
public class Demo {
public static void main(String[] args) {
//前面的变量就是一个接口
List<String> list = new ArrayList<>();
list = addName(list);
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
}
public static List<String> addName(List<String> list) {
list.add("蔡徐坤");
list.add("王源");
list.add("易烊千玺");
list.add("王俊凯");
return list;
}
}
标签:Java,String,--,void,list,接口,Hero,public,name
From: https://www.cnblogs.com/harper886/p/17411262.html