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
王兰