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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值