第六章 类(Class) 和对象(Object)
一、笔记导图
二、实例代码:
public class PrintCarStatus{ public static void main(String[] args){ int speed; String color; String name; String direction; speed = 200; color = "红色"; name = "法拉利"; direction = "纽博格林南环赛道"; System.out.println("经过的汽车的速度为:"+ speed); System.out.println("它的颜色是:"+ color); System.out.println("汽车的名字叫做"+ name); System.out.println("汽车的行驶方向为"+ direction); } }
//创建一个Car类,或定义Car类 public class Car{ int speed; String name; String color; String direction; }
public class UseCar { public static void main(String[] args) { Car carPassedBy; //1)声明一个Car类的变量 carPassedBy = new Car(); //2)创建一个Car类的实体 carPassedBy.speed = 60; //3)通过carPassedBy给Car实体的各个属性赋值 carPassedBy.color = "红色"; carPassedBy.name = "法拉利"; carPassedBy.direction = "纽博格林南环赛道"; System.out.println("经过的汽车的速度为:"+ carPassedBy.speed); //4)通过carPassedBy输出Car实体的各个属性的值 System.out.println("它的颜色是:"+ carPassedBy.color); System.out.println("汽车的名字叫做:"+ carPassedBy.name); System.out.println("汽车的行驶方向为:"+ carPassedBy.direction); } }
public class Plural{ int realPart; //保存复数实部的值 int virtualPart; //保存复数虚部的值 }
public class UsePlural{ public static void main(String[] args){ Plural a; //声明一个复数a a = new Plural(); //创建一个复数对象 a.realPart = 5; //给这个复数对象的realPart属性赋值 a.virtualPart = 10; //给这个复数对象的virtualPart属性赋值 System.out.println("复数的实部为"+ a.realPart); System.out.println("复数的虚部为"+ a.virtualPart); } }
public class Driver{ String name; //默认值为null int age; //默认缺省值为0 Car car; //默认值为null }
public class PrintDriverProps{ public static void main(String[] agrs){ Driver driver = new Driver(); /*System.out.println(driver.name); System.out.println(driver.age); System.out.println(driver.car); */ System.out.println(driver.age); if (driver.name !=null){ System.out.println("司机的名字为:" + driver.name); }else { System.out.println("没司机的名字"); } if (driver.car !=null){ System.out.println("司机的信息为:" + driver.car); }else { System.out.println("没司机的信息"); } } }
public class UseMotorcade{ public static void main(String[] args){ Motorcade groupCar = null; groupCar = new Motorcade(); groupCar.name = "一个车队"; int carCount = 5; groupCar.cars = new Car[5]; String direction = "镇江"; for (int i = 0;i < carCount; i++){ groupCar.cars[i] = new Car(); groupCar.cars[i].name = "汽车" + (i + 1); groupCar.cars[i].direction = direction; } System.out.println("车队的名称为:" + groupCar.name); System.out.println("车队中汽车的名字分别为:" + groupCar.name); for (int i = 0;i < carCount;i++){ System.out.println(groupCar.cars[i].name); } } }
三、练习题
public class UseBook{ public static void main(String[] args){ Book book = new Book(); book.bookName = "java从入门到放弃"; book.pageCount = 641; book.price = 74.5; System.out.println("这本书的书名为:" + book.bookName ); System.out.println("这本书页数共有:" + book.pageCount ); System.out.println("这本书的价格是:" + book.price ); } }