内部类
在类中间定义一个类,称为内部类。
成员类部类和区域内部类
public class PointDemo {
// 内嵌类
private class Point { //这个类编译好以后PointDemo$Point.class
private int x, y;
public Point() {
}
public void setPoint(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() { return x; }
public int getY() { return y; }
}
//内部类结束
private Point[] points;
public PointDemo(int length) {
points = new Point[length];
for(int i = 0; i < points.length; i++) {
points[i] = new Point();
points[i].setPoint(i*5, i*5);
}
}
public void showPoints() {
for(int i = 0; i < points.length; i++) {
System.out.printf("Point[%d]: x = %d, y = %d%n",
i, points[i].getX(), points[i].getY());
}
}
} public class PointShow {
public static void main(String[] args) {
PointDemo demo = new PointDemo(8);
demo.showPoints();
}
}
运行结果:
Point[0]: x = 0, y = 0
Point[1]: x = 5, y = 5
Point[2]: x = 10, y = 10
Point[3]: x = 15, y = 15
Point[4]: x = 20, y = 20
Point[5]: x = 25, y = 25
Point[6]: x = 30, y = 30
Point[7]: x = 35, y = 35
.
package 和 import
package onlyfun.caterpillar;
public class Point2D {
private int x;
private int y;
public Point2D() {
}
public Point2D(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() { return x; }
public int getY() { return y; }
}
package onlyfun.caterpillar;
public class PackageDemo {
public static void main(String[] args) {
System.out.println("Hello! World!");
}
}
import onlyfun.caterpillar.Point2D;
public class Point2DDemo2 {
public static void main(String[] args) {
Point2D p1 = new Point2D(10, 20);
System.out.printf("p1: (x, y) = (%d, %d)%n",
p1.getX(), p1.getY());
}
}
import 静态成员
import static 语法可以让你IMPORT 类或接口中的静态成员.可以声一些输入的时间
import static java.lang.System.out;//导入静态类
public class HelloWorld {
public static void main(String[] args) {
out.println("Hello! World!");
}
}
import static java.lang.System.out;
import static java.util.Arrays.sort;
public class ImportStaticDemo {
public static void main(String[] args) {
int[] array = {2, 5, 3, 1, 7, 6, 8};
sort(array);//不用Arrays.sort(array)
for(int i : array) {
out.print(i + " ");
}
}
}
import static java.lang.System.out;
import static java.util.Arrays.sort;
import static onlyfun.caterpillar.Arrays.sort;//用静态导入方法会造成名称的冲突
public class ImportStaticDemo2 {
public static void main(String[] args) {
int[] array = {2, 5, 3, 1, 7, 6, 8};
sort(array);
for(int i : array) {
out.print(i + " ");
}
}
}
编译出错: ImportStaticDemo2.java:9: 对 sort 的引用不明确,onlyfun.caterpillar.Arrays 中的 方法 sort(int[]) 和 java.util.Arrays 中的 方法 sort(int[]) 都匹配
sort(array);
^
1 错误