6.类
源文件声明规则
-
一个源文件只能有一个
public
类,可以有多个非public
类。 -
源文件的名字必须与
public
类的名字保持一致。 -
源文件先写
package
语句,再写import
语句
类的定义
public
:所有对象均可访问private
:只有本类内部可以访问protected
:同一个包或者子类中可以访问
如果不写,默认是:同一个包中可以访问。
- 静态成员变量、静态成员函数与C++是一致的。
举例说明:
package org.example.point;
public class Point
{
private int x;
private int y;
//构造函数
public Point(int x, int y)
{
//this指针
this.x = x;
this.y = y;
}
public Point()
{
this.x = -1;
this.y = -1;
}
public void setX(int x)
{
this.x = x;
}
public void setY(int y)
{
this.y = y;
}
public int getX()
{
return this.x;
}
public int getY()
{
return this.y;
}
public String toString()
{
return String.format(("(%d, %d)"), this.x, this.y);
}
}
类数组
申请类数组后,每一个变量还需要单独执行new
操作。
下列的ps
可以视作一个二维指针数组,申请了指针数组后并没有申请变量的地址。
public class Main {
public static void main(String[] args)
{
Point[] ps = new Point[3]; //此时ps[0~2]都是null
ps[0] = new Point(1, 2); //必须的,否则ps[0]会报错
System.out.println(ps[0].getX());
}
}
类的继承
每个类只能继承一个类,关键字:extends
。
调用父类构造函数的方法:super(arg1, ...)
。
package org.example.point;
public class ColorPoint extends Point
{
private String color;
public ColorPoint(int x, int y, String color)
{
//调用父类构造函数
super(x, y);
this.color = color;
}
public void setColor(String color)
{
this.color = color;
}
public String toString()
{
//调用父类的变量,需要使用super,因为变量在父类Point是private
return String.format(("(%d, %d, %s)"), super.getX(), super.getY(), color);
}
}
类的多态
子类继承父类的函数,自身也可以进行重写,若调用会优先调用子类重写的函数。
子类继承自父类,可以使用父类类型进行使用。
public class Main {
public static void main(String[] args) {
Point point = new Point(3, 4);
Point colorPoint = new ColorPoint(1, 2, "red");
// 多态,同一个类的实例,调用相同的函数,运行结果不同
//第一个输出 3,4
//第二个输出 1,2,red
System.out.println(point.toString());
System.out.println(colorPoint.toString());
}
}
补充一个不太一样的例子:
类对象的赋值相当于C++中的引用。
public class Main { public static void main(String[] args) { Point p = new Point(1, 2); Point cp = p; //该语句相当于引用 //修改cp中的变量,也会同步修改p cp.setX(3); System.out.println(p.toString()); } }