java 面向对象入门

发布于:2024-03-27 ⋅ 阅读:(67) ⋅ 点赞:(0)

类的创建

右键点击对应的包,点击新建选择java类

 填写名称一般是名词,要知道大概是什么的名称,首字母一般大写

 

 下面是创建了一个Goods类,里面的成员变量有:1.编号(id),2.名称(name)3.价格(price),4数量(count)

public class Goods {
    private String id;
    private String name;
    private double price;
    private int count;

 构造方法

一般写两个,一个是空参构造,另一个是带全部参数的构造,(写两个的原因是方便使用者使用

两种构造方法的名字一样,叫做构造方法的重载,

构造方法名一般与类名一样

空参构造:

 public Goods(){

    };

带全部参数的构造:

 public Goods(String id, String name, double price, int count){
        this.id=id;
        this.name=name;
        this.price=price;
        this.count=count;
    }

对应成员变量的get和set方法

get方法就是得到对象内成员变量,set类似给成员变量进行赋值的操作

 public String getId() {
        return id;
    }
    public void setId(String id){
        this.id=id;
    }
    public String getName(){
        return name;
    }
    public void setName(String name){
        this.name=name;
    }
    public double getPrice(){
        return price;
    }
    public void setPrice(double price){
        this.price=price;
    }
    public int getCount(){
        return count;
    }
    public void setCount(int count){
        this.count=count;
    }

对象的创建

在一个类建立后,就可以在主类里面创建对应的对象了

类就像一个设计图一下,而对象就是一个根据类来创建的一个实体,类是不占用内存的,对象是占用内存的

创建格式 

 下面是空参构造方法,意思就是没有对对象里面的成员变量进行初始化

Goods r1=new Goods();

下面是全部参数构造方法

Goods r1=new Goods("001","保温杯",233.9,100);

意思是创建了一个对象商品,编号为001,商品名字是保温杯,价格为233.9,数量为100个

以下是完整的Javabean类创建的商品类代码

package test2;

public class Goods {
    private String id;
    private String name;
    private double price;
    private int count;
    public Goods(){

    };
    public Goods(String id, String name, double price, int count){
        this.id=id;
        this.name=name;
        this.price=price;
        this.count=count;
    }

    public String getId() {
        return id;
    }
    public void setId(String id){
        this.id=id;
    }
    public String getName(){
        return name;
    }
    public void setName(String name){
        this.name=name;
    }
    public double getPrice(){
        return price;
    }
    public void setPrice(double price){
        this.price=price;
    }
    public int getCount(){
        return count;
    }
    public void setCount(int count){
        this.count=count;
    }
}

 

 下面的主类里面创建了三个商品对象并进行初始化,循环打印商品的所以成员变量

package test2;

public class GoodTest {
    public static void main(String[] args) {
   //创建一个数组
    Goods[] arr=new Goods[3];

    //创建三个商品对象
    arr[0]=new Goods("001","华为p40",5999.0,100);
    arr[1]=new Goods("002","保温杯",233.0,50);
    arr[2]=new Goods("003","枸杞",12.3,70);

    //遍历并打印结果
    for(int i=0;i<arr.length;i++){
        System.out.printf("%s,%s,%.2f,%d",arr[i].getId(),arr[i].getName(),arr[i].getPrice(),arr[i].getCount());
        System.out.println();
    }

    }
}

本文含有隐藏内容,请 开通VIP 后查看

网站公告

今日签到

点亮在社区的每一天
去签到