定义类的语法:[修饰符] class 类名{定义构造方法;定义属性;定义方法}
修饰符:public,final,abstract
1.定义英雄类
public class Hreo {
String name;
char sex;
public void sun() {
System.out.println(name+"正在奔跑");
}
public static void main(String[] args) {
Hreo hreo = new Hreo();
hreo.name="黑暗游侠";
hreo.sex='M';
hreo.sun();
}
}
2.创建Dota游戏中的防御塔类
package CSDN;
public class TowerDefense {
int x;
int y;
public void Location() {
System.out.printf("防御塔的坐标是(%d,%d)", x,y);
}
public static void main(String[] args) {
TowerDefense td=new TowerDefense();
td.x=20;
td.y=50;
td.Location();
}
}
方法的声明:[<修饰符>]<返回类型><方法名>([参数列表]){方法体}
3.定义添加英雄攻击方法
public class Hreo {
String name;
char sex;
int atk;
public void Sun() {
System.out.println(name+"正在奔跑");
}
public void battle() {
System.out.println(name+"发动了攻击");
}
public static void main(String[] args) {
Hreo hreo = new Hreo();
hreo.name="黑暗游侠";
hreo.sex='M';
hreo.Sun();
hreo.battle();
}
}
4.定义英雄的战斗方式
import java.util.Scanner;
public class Hreo {
String name;
char sex;
int output;
public void battle() {
output-=10;
}
public void hreo() {
Scanner sc = new Scanner(System.in);
System.out.println("请输入英雄的血量[1~100]:");
output = sc.nextInt();
}
public static void main(String[] args) {
int num=1;
Hreo hreo = new Hreo();
hreo.hreo();
do {
hreo.battle();
num++;
System.out.println("第"+num+"次攻击,您的英雄当前血量为"+hreo.output);
}while(hreo.output>0);
System.out.println("您的英雄已经牺牲");
}
}
5.可变形参方法
语法:[<修饰符>]<返回类型><方法名>(变量类型...变量名){方法体}
"..."表明该形参可以接受多个参数值,多个参数值被挡成数组传入。
package CSDN;
public class TestCal {
public int add(int...nums) {
int sum = 0;
for(int i:nums) {
sum += i;
}
return sum;
}
public static void main(String[] args) {
TestCal tc = new TestCal();
System.out.println(tc.add(3,6));
System.out.println(tc.add(new int[] {3,4,5}));
}
}