【Java语法基础】6.类

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());
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

指针常量

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值