java学习笔记09-类与对象

物以类聚,人以群分,我们把具有相似特性或品质的物体归为一类。

类:类是一种模板,它描述一类对象的行为和状态。

对象:对象是类的一个实例,有状态和行为。

比如在一支nba球队中,每个球员都有球衣号码,场均得分,司职位置。每个球员都有共同的行为打篮球。那么我们可以抽取出一个篮球运动员的类

类的定义

在java语言中,使用class关键字来定义一个类

package lesson;

public class Player {

}

这样就定义了一个类,public是访问修饰符,表示这个类可以在其他地方都可以访问。Player是类名

在ide工具,先创建一个包。然后在这个包下面创建class文件,会自动创建对应类

成员变量

运动员都有球衣号码,得分,司职等属性。这在java类中可以表示为成员变量

package lesson;

public class Player {
    public int number;  //号码
    public int score;   //得分
    public String position; //司职
}

声明成员变量的方式和普通变量的方式没有太大区别。只是可以在前面加上访问修饰符。并且声明在类中,不是在某个方法里。

方法

运动员都有一些行为,比如打篮球。这种行为可以在java类中表示为方法

package lesson;

public class Player {
    public int number;  //号码
    public int score;   //得分
    public String position; //司职

    public void playBall(){
        System.out.println("我是"+this.number+"号,我司职"+this.position
                +",这场我得到"+this.score+"分");
    }
}

这样就添加了一个打篮球的方法

构造方法

类只是一个模板而已,要想能够使用,需要通过这个模板创建对象。类提供了一种方法专门用于创建对象。这种方法叫做构造方法,每个类都有一个默认的构造方法,方法名与类名一直。并且没有放回类型。

创建对象

new 构造方法() 通过这样的语句就可以创建一个对象,但是这样创建好的对象,在接下来是引用不到。所以需要给这个对象起一个名字。所以一般来说,是这样做的。

类名 对象名 = new 构造方法()

对象的运用

创建了对象后,可以根据需求来使用对象了。

给属性赋值的方式是:类名.属性名=值

调用方法的方式是:类名.方法名(参数)

package lesson;

public class Player {
    public int number;  //号码
    public int score;   //得分
    public String position; //司职

    public void playBall(){
        System.out.println("我是"+this.number+"号,我司职"+this.position
                +",这场我得到"+this.score+"分");
    }
    public static void main(String[] args){
        Player player1 = new Player();
        player1.number = 11;
        player1.score = 19;
        player1.position = "中锋";
        player1.playBall();
    }
}

这样我们就创建了一个叫yaoming的对象。赋值了属性和调用了方法

this关键字

在类中表示当前对象。也就说不同对象调用这个方法,打印出来是对象自身的属性。再创建一个对象来看下效果

package lesson;

public class Player {
    public int number;  //号码
    public int score;   //得分
    public String position; //司职

    public void playBall(){
        System.out.println("我是"+this.number+"号,我司职"+this.position
                +",这场我得到"+this.score+"分");
    }
    public static void main(String[] args){
        Player player1 = new Player();
        player1.number = 11;
        player1.score = 19;
        player1.position = "中锋";
        player1.playBall();

        Player player2 = new Player();
        player2.number = 1;
        player2.score = 13;
        player2.position = "得分后卫";
        player2.playBall();

    }
}

猜你喜欢

转载自blog.csdn.net/a54288447/article/details/89402036