Java-类与对象的关系

白衣少年
2022-10-28 / 0 评论 / 51 阅读 / 正在检测是否收录...
温馨提示:
本文最后更新于2022年11月07日,已超过536天没有更新,若内容或图片失效,请留言反馈。
  • 类是一种抽象的数据类型,它是对某一类事物整体描述/定义,但是并不能代表某一个具体的事物.

    • 动物、植物、手机、电脑......
    • Person类、Pet类、Car类等,这些类都是用来描述/定义某一类具体的事物应该具备的特点和行为

类与对象的关系.png

  • 对象是抽象概念的具体实例

    • 张三就是人的一个具体实例,张三家里的旺财就是狗的一个具体实例。
    • 能够体现出特点,展现出功能的是具体的实例,而不是一个抽象的概念.

重要:一个类即使什么也不写,也是一个方法

示例代码:

Student类【方法】

//学生类
public class Student {
    //属性:字段
    String name;
    int age;

    //方法
    public void study(){
        System.out.println(this.name+"在学习");
    }

}

Application类【实现类】

//一个项目应该只存一个main方法
public class Application {
    public static void main(String[] args) {
        //类:抽象的,实例化
        //类实例化后会返回一个自己的对象!
        //student对象就是一个student类的具体实例!
        Student xiaoming = new Student();
        Student xiaohong = new Student();

        xiaoming.name="小明";
        xiaoming.age=18;

        System.out.println(xiaoming.name);
        System.out.println(xiaoming.age);

        xiaohong.name="小红";
        xiaohong.age=17;

        System.out.println(xiaohong.name);
        System.out.println(xiaohong.age);

    }
}
5

打赏

评论 (0)

OwO
取消