JAVA面向对象程序设计

定义类的语法:[修饰符] 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}));

	}

}

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值