回顾类 对象 构造器 ArrayList的基本使用
Animal类
package com.renzen.Animal.Day1; public class Animal { private String name; private String sex; //有参构造器 public Animal(String name, String sex) { this.name = name; this.sex = sex; } //无参构造器 public Animal() { } //get set public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } }
Test
package com.renzen.Animal.Day1; import java.util.ArrayList; public class Test { public static void main(String[] args) { //创建动物类ArrayList 集合 ArrayList<Animal> list=new ArrayList<>(); //创建Animal实例 Animal animal=new Animal("金毛","公"); Animal animal1=new Animal("牧羊犬","母"); list.add(animal); list.add(animal1); for (int i = 0; i < list.size(); i++) { System.out.println("品种 \t" + list.get(i).getName() + "性别\t" + list.get(i).getSex()); } } }
Car 类
package com.renzen.Animal.Day1; public class Car { private String name; private double price; //无参构造器 public Car() { } //有参构造器 public Car(String name,double price){ //如果不用this 则name不能给name赋值 //如果不用this 则price不能给price赋值 //name=name; //price=price; this.name=name; this.price=price; } //run public void run(String name){ System.out.println(this.name+"在和"+name+"比赛"); } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } }
Test
package com.renzen.Animal.Day1; public class Test1 { public static void main(String[] args) { Car c1=new Car("张三",121212); //当类名中不用this指定时 System.out.println(c1.getName());//null System.out.println(c1.getPrice());//0.0 System.out.println(c1.getName());//张三 System.out.println(c1.getPrice());//121212 c1.run("宝马"); } }
封装 个人 理解 就是 private 私有化成员属性 对外暴露set/get方法堆私有属性进行修改
Person类
package com.renzen.Animal.Day1; public class Person { private int age; //无参构造器 public Person(){ } //有参构造器 public void Person(int age){ this.age=age; } //get set public void setAge(int age){ if(age>0 && age<100){ this.age=age; }else{ System.out.println("age输入值有问题"); } } public int getAge(){ return this.age; } }
Test类、
package com.renzen.Animal.Day1; public class Test3 { public static void main(String[] args) { Person p=new Person(); System.out.println(p.getAge());//0 p.setAge(18); System.out.println(p.getAge());//18 } }