类和对象的定义以及使用

1. 类和对象的基本概念

1.1 JAVA是面向对象语言

Java是一门纯面向对象的语言(Object Oriented Program,简称OOP),在面向对象的世界里,一切皆为对象。面向对象是解决问题的一种思想,主要依靠对象之间的交互完成一件事情

1.2 类和对象的描述

在Java中万物皆对象,一切都围绕对象进行:

:把具有相同属性和行为的一类对象抽象为类。类是抽象概念,如人类、犬类等,无法具体到每个实体。
对象:某个类的一个实体,当有了对象后,这些属性便有了属性值,行为也就有了相应的意义。

类是对象的抽象,而对象是类的具体实例。类是抽象的,不占用内存,而对象是具体的,占用存储空间

做个比方:类实例化出对象就像现实中使用建筑设计图建造出房子,类就像是设计图,只设计出需要什么东西,但是并没有实体的建筑存在,同样类也只是一个设计,实例化出的对象才能实际存储数据,占用物理空间。
在这里插入图片描述

2. 类与对象的定义与使用

面向对象程序设计关注的是对象,而对象是现实生活中的实体,比如:狗。但是狗计算机并不认识,需要开发人员告诉给计算机什么是狗。
在这里插入图片描述
上图右侧就是对狗简单的描述,该过程称为对狗对象(实体)进行抽象(对一个复杂事物的重新认知),但是这些简化的抽象结果计算机也不能识别,开发人员可以采用某种面向对象的编程语言来进行描述,比如:Java语言。

2.1 类的定义格式

在java中定义类时需要用到class关键字,class为定义类的关键字,ClassName为类的名字,{}中为类的主体。具体语法如下:

// 创建类
class ClassName{  
    field;       // 字段(属性) 或者 成员变量
    method;      // 行为 或者 成员方法
}

类中包含的内容称为类的成员。属性主要是用来描述类的,称之为类的成员属性或者类成员变量。方法主要说明类具有哪些功能,称为类的成员方法。

2.2 类的实例化(对象的创建)

定义了一个类,就相当于在计算机中定义了一种新的类型,有了这些自定义的类型之后,就可以使用这些类来定义实例(或者称为对象)。用类类型创建对象的过程,称为类的实例化,在java中采用new关键字,配合类名来实例化对象。

类名称 对象名称 = new 类名称();

PetDog dogs = new PetDog();

注意事项
new 关键字用于创建一个对象的实例.

2.3 举个例子

采用Java语言定义狗类型,并创建一个狗的对象
在这里插入图片描述

class PetDog {
	//成员变量(实例变量),在堆中的每个对象中存储,通过对象调用
	// 狗的属性
    public String name;//名字
    public String color;//颜色
    
    //成员方法(实例方法),在JVM的方法区中存储,通过对象调用
    // 狗的行为
    public void barks() {
        System.out.println(name + ": 旺旺旺~~~");
   }
    public void wag() {
        System.out.println(name + ": 摇尾巴~~~");
   }
}

在这里插入图片描述

public class Main{
 public static void main(String[] args) {
 		//创建一个实例化对象,通过new实例化对象
        PetDog dogh = new PetDog();   
        //通过对象来调用实例变量、成员方法  
        dogh.name = "阿黄";
        dogh.color = "黑黄";
        dogh.barks();
        dogh.wag();
        
        PetDog dogs = new PetDog();
        dogs.name = "阿黄";
        dogs.color = "黑黄";
        dogs.barks();
        dogs.wag();
 }
}
 
输出结果:
阿黄: 旺旺旺~~~
阿黄: 摇尾巴~~~
赛虎: 旺旺旺~~~
赛虎: 摇尾巴~~~

注意事项:

  • 类名注意采用大驼峰定义
  • 一般一个文件当中只定义一个类
  • main方法所在的类一般要使用public修饰(注意:Eclipse默认会在public修饰的类中找main方法)
  • public修饰的类必须要和文件名相同 ,并且不要轻易去修改public修饰的类的名称。
  • 使用 . 来访问对象中的属性和方法.
  • 同一个类可以创建多个实例.

3. 对象的构造及初始化

3.1构造方法

3.1.1构造方法的定义

构造方法(也称为构造器)是一个特殊的成员方法,名字必须与类名相同,在创建对象时,由编译器自动调用,并且在整个对象的生命周期内只调用一次。

构造方法规则

  • 名字与类名相同,没有返回值类型,设置为void也不行
  • 一般情况下使用public修饰
  • 一个类中至少存在一个构造方法,若没有显示定义,编译器会生成一个默认的无参构造

示例代码:

public class Date {
    public int year;
    public int month;
    public int day;
 
    public Date(int year, int month, int day){
        this.year = year;
        this.month = month;
        this.day = day;
        System.out.println("Date(int,int,int)方法被调用了");
   }
 
    public void printDate(){
        System.out.println(year + "-" + month + "-" + day);
   }
 
    public static void main(String[] args) {
        // 此处创建了一个Date类型的对象,并没有显式调用构造方法
        Date d = new Date(2021,6,9);   // 输出Date(int,int,int)方法被调用了
        d.printDate();    // 2021-6-9
   }
}

使用new关键字产生一个对象时,大致分为以下两步(4.2中有详细过程):
(1)为对象在堆中分配空间(空间大小由该类中成员变量的属性决定)
(2)调用对象的构造方法为对象成员变量赋值(当构造方法调用结束后,该对象初始化完成),构造方法的作用就是对对象中的成员进行初始化,并不负责给对象开辟空间。

3.1.2 构造方法的特性

  1. 名字必须与类名相同
  2. 没有返回值类型,设置为void也不行
  3. 创建对象时由编译器自动调用,并且在对象的生命周期内只调用一次(相当于人的出生,每个人只能出生一次)
  4. 构造方法可以重载(用户根据自己的需求提供不同参数的构造方法)
class Date {
    public int year;
    public int month;
    public int day;
    
    // 无参构造方法
    public Date(){
        this.year = 1900;
        this.month = 1;
        this.day = 1;
   }
    // 带有三个参数的构造方法
    public Date(int year, int month, int day) {
        this.year = year;
        this.month = month;
        this.day = day;
   }

上述两个构造方法:名字相同,参数列表不同,因此构成了方法重载。

  1. 如果用户没有显式定义,编译器会生成一份默认的构造方法,生成的默认构造方法一定是无参的。
class Date {
    public int year;
    public int month;
    public int day;
 
    public void printDate(){
        System.out.println(year + "-" + month + "-" + day);
   }
 
    public static void main(String[] args) {
        Date d = new Date();
        d.printDate();
   }
}

在这里插入图片描述

上述Date类中,没有定义任何构造方法,编译器会默认生成一个不带参数的构造方法。

  1. 如果用户显式定义了构造方法,编译器则不会再生成构造方法。
class Date {
    public int year;
    public int month;
    public int day;
 
    public Date(int year, int month, int day) {
        this.year = year;
        this.month = month;
        this.day = day;
   }
}

public class Test{
    public static void main(String[] args) {
        // 如果编译器会生成,则生成的构造方法一定是无参的,则此处创建对象是可以通过编译的
        // 但实际情况是:编译期报错
        Date d = new Date();
   }
}

在这里插入图片描述

4.2 默认初始化

public class Date {
    public int year;
    public int month;
    public int day;
 
    public Date() {
        // 成员变量在定义时,并没有给初始值, 为什么就可以使用呢?
        System.out.println(this.year);
        System.out.println(this.month);
        System.out.println(this.day);
   }
    
    public static void main(String[] args) {
        // 此处a没有初始化,编译时报错:
        // Error:(24, 28) java: 可能尚未初始化变量a
        // int a;
        // System.out.println(a);
        Date d = new Date();
   }
}

在这里插入图片描述

我们观察上述代码部分,发现局部变量在使用时必须要初始化,而成员变量可以不用。要搞清楚这个问题的答案,就需要知道 new 关键字背后所发生的一些事情:

Date d = new Date();

在程序层面只是简单的一条语句,在JVM层面需要做好多事情,下面简单介绍下:

  1. 检测对象对应的类是否加载了,如果没有加载则加载

  2. 为对象分配内存空间

  3. 处理并发安全问题
    比如:多个线程同时申请对象,JVM要保证给对象分配的空间不冲突

  4. 初始化所分配的空间
    即:对象空间被申请好之后,对象中包含的成员已经设置好了初始值,比如:

数据类型默认值
byte0
char‘\u0000’
short0
int0
long0L
booleanfalse
float0.0f
double0.0
reference(引用类型)null
  1. 设置对象头信息
  2. 调用构造方法,给对象中各个成员赋值

5.4 就地初始化

在声明成员变量时,就直接给出了初始值。

public class Date {
    public int year = 1900;
    public int month = 1;
    public int day = 1;
 
    public Date(){
   }
 
    public Date(int year, int month, int day) {
   }
 
    public static void main(String[] args) {
        Date d1 = new Date(2021,6,9);
        Date d2 = new Date();
   }
}

注意:代码编译完成后,编译器会将所有给成员初始化的这些语句添加到各个构造函数中

4.this 关键字(表示当前对象的引用)

4.1 this.XXX调用当前对象的属性/字段/成员变量

class Date {
    public int year;
    public int month;
    public int day;

    public Date(int year, int month, int day) {
        year = year;
        month= month;
        day = day;
    }
    public void printDate() {
        System.out.println(year + "/" + month + "/" + day);
    }
}
public class Test{
    public static void main(String[] args) {
        // 构造日期类型的对象 d1
        Date d1 = new Date(2020, 9, 15);
        // 打印日期中的内容
        d1.printDate();
    }
}

在这里插入图片描述

以上代码定义了一个日期类,然后main方法中创建了三个对象,并通过Date类中的构造方法对对象成员变量进行初始化,但输出结果仍是默认值。
原因是这里传入的形参名 year和 month,day与 赋值的名字相同 ,编译器并不知情 ,会按照就近匹配原则,由于局部变量优先 ,此时就会出现自己赋值给自己的情况 。
在这里插入图片描述
this关键字表示当前对象的引用,使用this关键字可以调用当前对象的成员变量

class Date {
    public int year;
    public int month;
    public int day;
 
    public Date(int year, int month, int day){
        this.year = year;
        this.month = month;
        this.day = day;
   }
 
    public void printDate(){
        System.out.println(this.year + "/" + this.month + "/" + this.day);
   }
}

public class Test{
    public static void main(String[] args) {
        Date d1 = new Date(2020, 9, 15);
        // 打印日期中的内容
        d1.printDate();
    }
}

在这里插入图片描述

4.2 this.xxx()调用当前对象的成员方法

class Date {
    public int year;
    public int month;
    public int day;

    public Date(int year, int month, int day){
        this.year = year;
        this.month = month;
        this.day = day;
    }
    public void init() {
        System.out.println("Date的int()方法");
    }
    public void printDate(){
    //init()方法是成员方法,必须通过对象调用
	//this表示对象的引用,调用成员方法时不写,编译时也会自动加上
        init();//等价于this.init();
        System.out.println("Date的printDate()方法");
        System.out.println(this.year + "/" + this.month + "/" + this.day);
    }
}

public class Test{
    public static void main(String[] args) {
        Date d1 = new Date(2020, 9, 15);
        // 打印日期中的内容
        d1.printDate();
    }
}

在这里插入图片描述

4.3 this(XX,…)调用当前对象的其他构造方法

构造方法中,可以通过this调用其他构造方法来简化代码

class Date {
    public int year;
    public int month;
    public int day;
    
    // 无参构造方法--内部给各个成员赋值初始值,该部分功能与三个参数的构造方法重复
    // 此处可以在无参构造方法中通过this调用带有三个参数的构造方法
    // 但是this(1900,1,1);必须是构造方法中第一条语句
    public Date(){
        //System.out.println(year);   注释取消掉,编译会失败,this()是构造方法中第一条语句
        this(1900, 1, 1); 
        //等价于
        //this.year = 1900;
        //this.month = 1;
        //this.day = 1;
   }
 
    // 带有三个参数的构造方法
    public Date(int year, int month, int day) {
        this.year = year;
        this.month = month;
        this.day = day;
   }
}

注意事项

  • this(…)必须是构造方法中第一条语句
  • 不能形成环
public Date(){
   this(1900,1,1);
} 
public Date(int year, int month, int day) {
   this();
}
 
/*无参构造器调用三个参数的构造器,而三个参数构造器有调用无参的构造器,形成构造器的递归调用
编译报错:Error:(19, 12) java: 递归构造器调用*/

4.4 this引用

this引用指向当前对象(成员方法运行时调用该成员方法的对象),在成员方法中所有成员变量的操作,都是通过该引用去访问。只不过所有的操作对用户是透明的,即用户不需要来传递,编译器自动完成。

class Date {
    public int year;
    public int month;
    public int day;
 
    public void setDay(int year, int month, int day){
        this.year = year;
        this.month = month;
        this.day = day;
   }
 
    public void printDate(){
        System.out.println(this.year + "/" + this.month + "/" + this.day);
   }
}
public class Test{
	public static void main(String[] args) {
	    Date d = new Date();
	    d.setDay(2020,9,15);
	    d.printDate();
	}
}

注意:this引用的是调用成员方法的对象。
在这里插入图片描述

  1. this的类型:对应类类型引用,即哪个对象调用就是哪个对象的引用类型
  2. this只能在"成员方法"中使用
  3. 在"成员方法"中,this只能引用当前对象,不能再引用其他对象
  4. this是“成员方法”第一个隐藏的参数,编译器会自动传递,在成员方法执行时,编译器会负责将调用成员方法对象的引用传递给该成员方法,this负责来接收
    在这里插入图片描述

5.对象的打印

class Person {
    String name;
    String gender;
    int age;
 
    public Person(String name, String gender, int age) {
        this.name = name;
        this.gender = gender;
        this.age = age;
        }
 }
 public class Test{
    public static void main(String[] args) {
        Person person = new Person("Jim","男", 18);
        System.out.println(person);
   }
}
 
// 打印结果:day20210829.Person@1b6d3586

如果想要默认打印对象中的属性该如何处理呢?答案:重写toString方法即可。

class Person {
    String name;
    String gender;
    int age;
 
    public Person(String name, String gender, int age) {
        this.name = name;
        this.gender = gender;
        this.age = age;
   }
 
    @Override
    public String toString() {
        return "[" + name + "," + gender + "," + age + "]";
   }
}   
 public class Test{
    public static void main(String[] args) {
        Person person = new Person("Jim","男", 18);
        System.out.println(person);
   }
}
 
// 输出结果:[Jim,男,18]

6. 封装

6.1 封装的概念

面向对象程序三大特性:封装、继承、多态。而类和对象阶段,主要研究的就是封装特性.

封装:将数据和操作数据的方法进行有机结合,隐藏对象的属性和实现细节,仅对外公开接口来和对象进行交互

6.2 访问限定符

Java中主要通过类和访问权限来实现封装:类可以将数据以及封装数据的方法结合在一起,更符合人类对事物的认知,而访问权限用来控制方法或者字段能否直接在类外使用。Java中提供了四种访问限定符:
在这里插入图片描述
【说明】

  1. protected主要是用在继承中
  2. default权限指:什么都不写时的默认权限
  3. 访问权限除了可以限定类中成员的可见性,也可以控制类的可见性
public class Computer {
    private String cpu;          // cpu
    private String memory;       // 内存
    public String screen;        // 屏幕
    String brand;                // 品牌---->default属性
 
    public Computer(String brand, String cpu, String memory, String screen) {
        this.brand = brand;
        this.cpu = cpu;
        this.memory = memory;
               this.screen = screen;
   }
 
    public void Boot(){
        System.out.println("开机~~~");
   }
 
    public void PowerOff(){
        System.out.println("关机~~~");
   }
 
    public void SurfInternet(){
        System.out.println("上网~~~");
   }
}
 
public class TestComputer {
    public static void main(String[] args) {
        Computer p = new Computer("HW", "i7", "8G", "13*14");
        System.out.println(p.brand);     // default属性:只能被本包中类访问
        System.out.println(p.screen);    // public属性: 可以任何其他类访问
        // System.out.println(p.cpu);       //err, private属性:只能在Computer类中访问,不能被其他类访问
   }
}

注意:一般情况下成员变量设置为private,成员方法设置为public。

7. static关键字

7.1 static修饰成员变量

static修饰的成员变量,称为静态成员变量,静态成员变量最大的特性:不属于某个具体的对象,是所有对象所共享的。

静态成员变量特性】
1. 不属于某个具体的对象,是类的属性,所有对象共享的,不存储在某个对象的空间中
2. 既可以通过对象访问,也可以通过类名访问,但一般更推荐使用类名访问
3. 类变量存储在方法区当中
4. 生命周期伴随类的一生(即:随类的加载而创建,随类的卸载而销毁)

public class Student{
    public String name;
    public String gender;
    public int  age;
    public double score;
    public static String classRoom = "Bit306";
    
    // ...
    
    public static void main(String[] args) {
        // 静态成员变量可以直接通过类名访问
        System.out.println(Student.classRoom);
 
        Student s1 = new Student("Li leilei", "男", 18, 3.8);
        Student s2 = new Student("Han MeiMei", "女", 19, 4.0);
        Student s3 = new Student("Jim", "男", 18, 2.6);
 
        // 也可以通过对象访问:但是classRoom是三个对象共享的
        System.out.println(s1.classRoom);
        System.out.println(s2.classRoom);
        System.out.println(s3.classRoom);
        }
}

调试方式运行上述代码,然后在监视窗口中可以看到,静态成员变量并没有存储到某个具体的对象中。

7.2 static修饰成员方法

一般类中的数据成员都设置为private,而成员方法设置为public,那设置之后,Student类中classRoom属性如何在类外访问呢?

public class Student{
    private String name;
    private String gender;
    private int  age;
    private double score;
    private static String classRoom = "Bit306";
    
    // ...
}
 
public class TestStudent {
    public static void main(String[] args) {
        System.out.println(Student.classRoom);
   }
}
 
编译失败:
Error:(10, 35) java: classRoom 在 extend01.Student 中是 private 访问控制

Java中,被static修饰的成员方法称为静态成员方法,是类的方法,不是某个对象所特有的。静态成员一般是通过静态方法来访问的。

public class Student{
    // ...
    
    private static String classRoom = "Bit306";
    
    // ...
    
    public static String getClassRoom(){
        return classRoom;
   }
}
 
public class TestStudent {
    public static void main(String[] args) {
        System.out.println(Student.getClassRoom());
   }
}

输出:Bit306

【静态方法特性】
1. 不属于某个具体的对象,是类方法
2. 可以通过对象调用,也可以通过类名.静态方法名(…)方式调用,更推荐使用后者
3. 不能在静态方法中访问任何非静态成员变量

public static String getClassRoom(){
    System.out.println(this);
    return classRoom;
}
 
// 编译失败:Error:(35, 28) java: 无法从静态上下文中引用非静态 变量 this
 
public static String getClassRoom(){
    age += 1;
    return classRoom;
}
 
// 编译失败:Error:(35, 9) java: 无法从静态上下文中引用非静态 变量 age

4. 静态方法中不能调用任何非静态方法,因为非静态方法有this参数,在静态方法中调用时候无法传递this引用

public static String getClassRoom(){
    doClass();
    return classRoom;
}
 
// 编译报错:Error:(35, 9) java: 无法从静态上下文中引用非静态 方法 doClass()

5. 静态方法无法重写,不能用来实现多态

7.4 static成员变量初始化

注意:静态成员变量一般不会放在构造方法中来初始化,构造方法中初始化的是与对象相关的实例属性,静态成员变量的初始化分为两种:就地初始化静态代码块初始化。

  1. 就地初始化
    就地初始化指的是:在定义时直接给出初始值
public class Student{  
    private static String classRoom = "Bit306";   
    // ...
}
  1. 静态代码块初始化
public class Student{    
	private static String classRoom; 
	// 静态代码块
    static {
        classRoom = "bit306";
        System.out.println("I am static init()!");
   }
  • 25
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值