普通代码
public static void main(String[] args) {
int a [] = {10,20,30,40,50};
int max=a[0];
for (int i = 1; i < a.length; i++) {
if( a[i]>max ){
max=a[i];
}
}
System.out.println("最大值:"+max);
}
封装代码
public static void main(String[] args) {
int a[] = {10, 20, 30, 40, 50};
int max = method(a);
System.out.println("最大值:"+max);
}
public static int method(int[] a) {
int max = a[0];
for (int i = 1; i < a.length; i++) {
if (a[i] > max) {
max = a[i];
}
}
return max;
}
private
类代码
public class demo03Person {
String name ;
private int age ;
public void show(){
System.out.println("我叫"+name+",年龄"+age);
}
public void setAge(int sum ){
if (sum<100&&sum>0){
age=sum;
}
else{
System.out.println("数据不合理");
}
}
public int getAge(){
return age;
}
对象代码
public static void main(String[] args) {
demo03Person one = new demo03Person();
one.show();
one.name="lcz";
// one.age=20; //错误使用
one.setAge(20);
one.show();
}
练习使用private创建一个学生类
类代码
public class Student {
private String name ;
private int age ;
private boolean male ;
public void setMale(boolean man){
male=man;
}
public boolean isMale(){
return male;
}
public void setAge(int sum){
age=sum;
}
public int getAge(){
return age;
}
public void setName(String str){
name=str;
}
public String getName(){
return name;
}
对象代码
public static void main(String[] args) {
Student one = new Student();
one.setName("郭哈哈");
one.setAge(20);
one.setMale(true);
System.out.println("名字:"+one.getName());
System.out.println("年龄:"+one.getAge());
System.out.println("是不是爷们儿:"+one.isMale());
}