Java - Classes and Objects - More on Classes
Classes and Objects
More on Classes
本结主要讲:
- Return在方法中的使用
- This 关键字
- 类成员和实例成员
- 访问控制(类成员)
Returning a Value from a Method
方法在调用时遇到以下的情况会返回到调用它的代码:
- 执行完方法内的所有语句
- 执行到 return 语句
- 或者抛出错误
return属于分支语句 可以用来退出控制流语句的其中一个分支,同时退出方法。
如果试图从声明为void的方法返回值,则会得到编译器错误。
return只可以返回规定的类或者规定的类的子类,如图:

方法可以返回一个ImaginaryNumber,但不能返回Object。ImaginaryNumber是一个Number,因为它是Number的子类。但是,Object不一定是Number—它可以是String或其他类型。
注意:您也可以使用接口名称作为返回类型。在这种情况下,返回的对象必须实现指定的接口。
Using the this Keyword
Using this with a Field
this最常见的用法:
public class Point {
public int x = 0;
public int y = 0;
//constructor
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}
不用this:
public class Point {
public int x = 0;
public int y = 0;
//constructor
public Point(int a, int b) {
x = a;
y = b;
}
}
Using this with a Constructor
在构造函数内部,还可以使用this关键字调用同一类中的另一个构造函数。这样做被称为显式构造函数调用,编译器根据参数的数量和类型决定调用哪个构造函数。如下例:
public class Rectangle {
private int x, y;
private int width, height;
public Rectangle() {
//this调用其他构造函数需要在当前构造函数的第一行
this(0, 0, 1, 1);
}
public Rectangle(int width, int height) {
//this调用其他构造函数需要在当前构造函数的第一行
this(0, 0, width, height);
}
public Rectangle(int x, int y, int width, int height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
...
}

浙公网安备 33010602011771号