008类和对象

1:类和对象的概念

类是现实世界当中具有共同特征的事物进行抽象形成的模板或概念。而对象是实际存在的
个体。

通过类可以创建对象,对象又被称为实例(instance),这个过程也可以称为实例化。

 

2:类的定义

[修饰符]  class 类名{

  类体 = 属性 + 方法

}

public class student{            //定义一个student类
    int id;
    String name;
}

 

3 对象的创建

new 类名()

public class student {

    public static void main(String[] args) {

        new student();                //创建一个student对象
    }

}

为了使用对象更加方便,建议使用变量接收一下?例如以下代码:

public class student {

    public static void main(String[] args) {

        student s1 = new student();                //创建一个student对象
        
        student s2 = new student();
    }

}

student s1 = new student() 实际上和 int i = 10 类似,对于 int i = 10 来说,int 时变量名 ,10 是 int 类型的字面量。那对于student s1 = new student() 来说,其中 student 是一种引用数据类型,s1 是变量名,new student() 执行之后是一个student 类型的对象

 

4 当实例变量是一个引用:

public class test1 {
    int id = 0010;                        
    int age = 20;
    String name = "张三";
    
}

在以上代码中,idage 的类型都是 int 类型的变量,int 是基本数据类型,所以 id 中存的就是0010,age 中存的就是20,

而 name 变量是 String 类型,String类型不是基本数据类型,他是引用数据类型。

String name = "张三"; 实际上,name 变量中存储的并不是"张三" 这个字符串,因为 name 是一个引用,所以它存储的是"张三" 字符串的对象的内存地址。

什么是引用?

  引用就是一个变量,只不过该变量中存储的是 java 对象的内存地址。

posted @ 2021-04-20 16:36  南昌故郡  阅读(52)  评论(0)    收藏  举报