2021-03-23

java的三大特性:封装、继承、多态
1.封装

public class mian {
	public static void main(String[] args) {
	int[] array = {5,10,15,20,25};
	int max = getMox(array);
	System.out.println("最大值:"+max);
	}
	//给一个数组,得到一个最大值
	public static int getMox(int[] array) {
		int max = array[0];
		for (int i = 1;i < array.length;i++) {
			if(array[i] > max) {
				max = array[i];
			}
		}
		return max;
	}
}

计算结果:max为25
2.变量
1.位置不一样
局部变量 在方法内
成员变量 在类里面
2.作用范围不一样
3.默认值不一样
局部变量 必须初始化
成员变量 不用初始化
4.在内存中的位置不一样
局部变量 在栈里面
成员变量 在堆里面
5.生命周期不一样
定义代码:

public class tomoro {
	String name;
	short num2;
	int a;
	int b;
		public void drive() {
			int num = 20;
			System.out.println(num);
			System.out.println(name);
			System.out.println(num2);
		}
}

使用代码:

public class stre {
	public static void main(String[] args) {
		tomoro var1 = new tomoro();
		var1.drive();
		System.out.println(var1.name);
		System.out.println(var1.num2);
	}
}

运行结果:
20
null
0
null
0

3.继承、多态
定义代码:

public class vcl {
	String name;//姓名
	private int age;//年龄
	private boolean male;//true 是男性
	public void setMale(boolean boy) {
		male = boy;
	}
	public boolean isMale() {
		return male;
	}
	//这种成员方法专门用于向set设置数据使用
	//1.保障数据的私有和安全;
	//2.保证数据的合理性。
	public void setAge(int num) {
		if (num < 150 && num >=0) {//如果是合理情况
			age = num;
		}else {
			System.out.println("数据不合理!");
		}
	}
	//这种成员方法专用于私语获取age的数据
	public int getAge() {
		return age;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getName() {
		return name;
	}
	public void show() {
		System.out.println("我是"+name+",年龄"+age);
	}
}

使用代码;(分开运行的代码)
1.

public class vci {
	public static void main(String[] arge) {
		vcl person = new vcl();
		person.show();
		person.name = "何婷";
		//在类的外部不能直接访问。
		person.setAge(18);
		person.show();
		person.setAge(19);
		int age1;
		age1 = person.getAge();
		System.out.print(person.getName());
		System.out.println(age1);
	}
}

运行结果:
我是null,年龄0
我是何婷,年龄18
何婷19

2.

public class vcj {
	public static void main(String[] args) {
		vcl person = new vcl();
		person.show();
		person.name = "何婷";
		person.setAge(18);
		person.setMale(true);
		System.out.println(person.getName());
		System.out.println(person.getAge());
		System.out.println(person.isMale());
		
		person.setName("王兰");
		System.out.println(person.getName());
	}
}

运行结果:
我是null,年龄0
何婷
18
true
王兰

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值