Java基础-类与对象
第六章 介绍类
一、类基础
类就是对象的模板(template),而对象就是类的 一个实例(instance)
1.类的基础格式
使用关键字class来创建类
2.一个简单类
一个类定义一个新的数据类型
class Box{
double width;
double height;
double depth;
}
//要想真正创建按一个Box对象,必须创建一个对象(实例)
Box mybox = new Box();//Create a Box object called mybox;
上述例子有三个变量:width height depth
要想访问这三个变量,你需要使用点运算符(dot operator) “ . ”
mybox.width = 100;//使用点运算符使用
下面是Box的完整程序:
/*
A program that uses the Box class.
Call this file BoxDemo.java
*/
class Box {
double width; double height; double depth;
}
// This class declares an object of type Box.
class BoxDemo {
public static void main(String args[]) {
Box mybox = new Box(); double vol;
// assign values to mybox's instance variables
mybox.width = 10; mybox.height = 20; mybox.depth = 15;
// compute volume of box
vol = mybox.width * mybox.height * mybox.depth;
System.out.println("Volume is " + vol);
}
}
每个对象都有自己的、由它的类定义的实例变量的拷贝,改变一个对象的实例变量对另一个对象的实例变量没有任何影响:
//This program declare two Box objects
class Box{
double width; double height; double depth;
}
class BoxDemo2{
public static void main(String args[]){
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
//assign values to mybox1's instance variables
mybox1.width = 10; mybox1.heigth = 20; mybox1.depth = 15;
//assign different values to mybox2's instance variables
mybox2.width = 3; mybox2.heigth = 6; mybox2.depth = 9;
//compute volume of box1
vol = mybox1.width * mybox1.height * mybox1.depth;
System.out.println("Volueme1 is" + vol);
//compute volume of box2
vol = mybo2.width * mybox2.height * mybox2.depth;
System.out.println("Volueme2 is" + vol);
}
}
结果:
Volume is 3000.0
Volume is 162.0
可以看见,两个box的值互不干扰
二、声明对象
Box mybox;//declare reference to object
mybox = new Box();//allocate a Box object
第一行声明了mybox,把它作为对于Box类型的对象的引用,mybo