Java 类
Java教程 - Java类
类定义了一种新的数据类型。
此新类型可用于创建该类型的对象。
类是对象的模板,对象是类的实例。
语法
类定义的一般形式如下所示:
class classname {
type instance-variable1;
type instance-variable2;
// ...
type instance-variableN;
type methodname1(parameter-list) {
// body of method
}
type methodname2(parameter-list) {
// body of method
}
// ...
type methodnameN(parameter-list) {
// body of method
}
}
使用class关键字声明一个类。
在类中定义的方法和变量称为类成员。
类中定义的变量称为实例变量因为类的每个实例都包含这些变量的自己的副本。
一个对象的数据是独立的,并且与另一个对象的数据唯一。
例子
这里有一个名为 Box 的类,它定义了三个成员变量: width , height 和 depth 。
class Box {
int width;
int height;
int depth;
}
Java对象
创建类时,将创建一个新的数据类型。您可以使用此类型来声明该类型的对象。
创建类的对象是一个两步过程。
- 声明类类型的变量。
- 使用new运算符动态分配对象的内存。
以下行用于声明一个类型为Box的对象:
Box mybox = new Box();
这个语句结合了这两个步骤。 它可以像这样重写来显示每个步骤更清楚:
Box mybox; // declare reference to object mybox = new Box(); // allocate a Box object
第一行声明 mybox 作为 Box 类型的对象的引用。此行执行后, mybox 包含值 null 。null表示 mybox 尚未指向实际对象。
此时尝试使用 mybox 会导致错误。
下一行分配一个实际对象并为mybox分配一个引用。第二行执行后,您可以使用mybox作为Box对象。
mybox 保存实际Box对象的内存地址。
类定义了一种新的数据类型。 在这种情况下,新类型称为 Box 。要创建 Box 对象,您将使用如下语句:
class Box {
int width;
int height;
int depth;
}
public class Main {
public static void main(String args[]) {
Box myBox = new Box();
myBox.width = 10;
System.out.println("myBox.width:"+myBox.width);
}
}
输出:

myBox 是 Box 的一个实例。 mybox 包含每个实例变量的自己的副本, width , height 和 depth 由类定义。 要访问这些变量,您将使用点(.)运算符。
mybox.width = 10;
此语句将宽度从 mybox 对象分配给 10 。这是一个使用 Box 类的完整程序:
任何尝试使用空的mybox将导致编译时错误。
class Box {
int width;
int height;
int depth;
}
public class Main {
public static void main(String args[]) {
Box myBox;
myBox.width = 10;
}
}
如果尝试编译上面的代码,您将从Java编译器获取以下错误消息。

Java instanceof运算符
Java提供了运行时运算符instanceof来检查对象的类类型。
instanceof运算符具有以下一般形式:
object instanceof type
以下程序演示 instanceof :
class A {
}
class B {
}
class C extends A {
}
class D extends A {
}
public class Main{
public static void main(String args[]) {
A a = new A();
B b = new B();
C c = new C();
D d = new D();
if (a instanceof A)
System.out.println("a is instance of A");
if (b instanceof B)
System.out.println("b is instance of B");
if (c instanceof C)
System.out.println("c is instance of C");
if (c instanceof A)
System.out.println("c can be cast to A");
if (a instanceof C)
System.out.println("a can be cast to C");
A ob;
ob = d; // A reference to d
System.out.println("ob now refers to d");
if (ob instanceof D)
System.out.println("ob is instance of D");
ob = c; // A reference to c
System.out.println("ob now refers to c");
if (ob instanceof D)
System.out.println("ob can be cast to D");
else
System.out.println("ob cannot be cast to D");
if (ob instanceof A)
System.out.println("ob can be cast to A");
// all objects can be cast to Object
if (a instanceof Object)
System.out.println("a may be cast to Object");
if (b instanceof Object)
System.out.println("b may be cast to Object");
if (c instanceof Object)
System.out.println("c may be cast to Object");
if (d instanceof Object)
System.out.println("d may be cast to Object");
}
}
此程序的输出如下所示:


免费 AI IDE


更多建议: