C++转Java日记(03)

this指针

接着你写的 Student 类,今天把 this、`private`、`static` 的区别弄清楚。先不加新功能,用你已经写过的代码理解它们。

this表示当前正在操作的对象。

如果参数换个名字,可以不写 this:

复制代码
Student(String studentName, int studentScore) {
    name = studentName;
    score = studentScore;
}

private 限制外部直接访问成员。

static 表示成员属于类,由所有对象共享。

静态方法不能访问普通成员变量,因为没有办法指定读取某个对象的数据。要这么读的话应该变成实例方法,通过对象调用才能读谁的。

小练习,这个输出多少?

java 复制代码
public class Main {
    public static void main(String[] args) {
        Student a=new Student(90);
        Student b=new Student(80);
        a.showInfo();
        b.showInfo();
    }
}
class Student{
    private static int score;
    Student(int score){
        Student.score=score;
    }
    void showInfo(){
        System.out.println("score:"+score);
    }
}

显然都是80。

不过我在此有了个疑问,Student这个构造函数,不能写this.score=score了吗?

可以这样写,能编译,但当 score 是静态字段时,不推荐。因为private static int score表示score属于类,即使通过this.score访问修改的仍然是共享的那一份。

所以这两种写法在这里修改的是同一个字段:

java 复制代码
this.score = score;    // 能用,但容易让人误以为是对象独有的字段
Student.score = score; // 推荐,明确表示这是静态字段

构造方法重载

它能解决你之前遇到的"有时传两个参数,有时传三个参数"的问题。

同一个类可以有多个构造方法,只要参数列表不同。

这叫 重载(overload) ,C++ 中也有这个概念。参数的数量、类型或类型顺序不同,可以形成重载;仅改参数名不算。

java 复制代码
    Student(String name, int score) {
        this(name, 20, score);
    }

    Student(String name, int age, int score) {
        this.name = name;
        this.age = age;
        this.score = score;
    }

问:this可以通过括号构造参数吗?然后怎么对应到这个20就是age的?

Java 找到参数类型依次为 String、int、int 的构造方法,然后按位置传递。

问:所以这个是严格按照位置定义的吗?如果是int string int,传入这个就会报错?

对,参数严格按位置匹配,而且每个位置的类型必须兼容。

假如你写反了:

复制代码
this(name, score, 20);

仍然能编译,因为后两个参数都是 int,但会得到:

复制代码
年龄:90
成绩:20
相关推荐
皮皮林5516 分钟前
Java实现微信扫码登录
java
布莱克60513 分钟前
C++ 中 map 的 insert 与 emplace:key 已存在时会覆盖吗?
开发语言·数据结构·c++·算法·map
xys_67831 分钟前
深挖C++:类和对象(中)
开发语言·c++
灿飞屋41 分钟前
Rust 编程其实很简单
开发语言·rust
Yyyyyy~3 小时前
【Java】Day4Web基础知识
java·spring boot
MOONICK3 小时前
QT元数据
开发语言·qt
D e re k ZH3 小时前
C++ 系统学习手记:从语法细节到工程实践
开发语言·数据结构·c++·算法
灿飞屋4 小时前
Kotlin与Java虚拟机三:控制流
android·java·开发语言·后端·python·kotlin·安卓
xiaoye-duck4 小时前
《C++ 项目:手写大模型接入 SDK》Ollama接口设计(上):初始化、全量响应实现和测试
开发语言·网络·c++·语言模型