类、对象及构造器

    类为Java编程语言中最基本单位,是具有相似属性的事物的总称。而对象是指生活中某一具体事物。需要注意,类为抽象,而对象为具体,所以在选择、描述对象时要找到其本质特征,通常从对象的属性、行为两方面着手!下面代码为阐述类,对象的关系及应用:

//定义一个Student类

public class Student{
    //定义姓名属性
     private String name;
     //定义血量属性
     public int score;
     //设置姓名属性值
     public void setname(String n){
         name=n;
         }
         //获取姓名
         public String getname(){
             return name;
         }
         //设置学分属性
         public void setscore(int b){
             score=b;
         }
         //获取学分
         public int getscore(){
             return score;
         }

     构造器的作用为设置类的对象并将对象初始化,简化程序。其使用关键字为“this”。代码如下:

//定义一个Student类

public class Student{

 //定义姓名属性
     private String name;
     //定义血量属性
     public int score;
     //设置姓名属性值

public Student(String name,int score)

      this.name=name;

      this.score=score;

}

//设置姓名可编辑

public void setname{

  this.name=name;

}

//获取姓名值

public String getname(){

  return name;

}

//设置分数可编辑

public void setscore{

  this.score=score;

}

//获取分数值

public String getscoree(){

  return score;

}

当使用构造器设置对象属性时,在以后调用对象时将不可更改!

 

 

你可能感兴趣的:(类、对象及构造器)