第六章 类(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("没司机的信息"); } } }
三、练习题