JAVA-类

文章目录

  • 类的构建

类的构建

package cn.liuli.ex1;

public class Main {
    public static void main(String[] args) {
        Student student = new Student();
        student.name = "chy";
        student.score = 100;
        System.out.println(student.name + "," + student.score);
        System.out.println(student.msg());
    }
}

class Student{
    public String name;
    public int score;

    public String msg(){
        return name + "," + score;
    }
}

程序出现错误后,系统会自动抛出异常;此外,Java 也允许程序自行抛出异常,自行抛出异常使用 throw 语句来完成。

 public void setScore(int score){
        if (score < 0 || score > 150 ){
            throw new IllformedLocaleException("score must between 0-150");
        }
        this.score = score;
    }

在Student 类里面调用private方法

    public String msg(){
        return name + "," + weightedScore();
    }
    
    private int weightedScore(){
        return int(this.score * 0.8 + 20);
    }
public class Main {
    public static void main(String[] args) {
        Student student = new Student();
        student.name = "chy";
        student.setScore(110);
        System.out.println(student.msg());
    }
}

class Student{
    public String name;

//    私有属性
    private int score;

	私有属性的设置
    public void setScore(int score){
        if (score < 0 || score > 150 ){
        	抛出异常
            throw new IllformedLocaleException("score must between 0-150");
        }
        this.score = score;
    }

	公共方法
    public String msg(){
        return name + "," + weightedScore();
    }

	私有方法
    private int weightedScore(){
        return (int)(this.score * 0.8 + 20);
    }
}

自动化私有属性方法

package cn.liuli.ex2;

public class Student {
    
    private String name;
    private int score;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setScore(int score) {
        this.score = score;
    }
}

封装数据

package cn.liuli.ex3;

import java.lang.reflect.Array;
import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        Group group = new Group();
        没有多余的引用
        group.setNames(new String[]  {"chy1","chy2","chy3"});
        System.out.println(group.msg());
    }
}
class Group{
    private String[] names;
    public void setNames(String[] names){
        this.names = names;
    }
    public String msg(){
        return Arrays.toString(this.names);
    }
}

你可能感兴趣的:(JAVA,java,jvm,开发语言)