如何使用参数化构造函数创建类的另一个实例

时间:2016-04-05 16:26:40

标签: constructor

  1. 测试您的计划
  2. 创建一个名为Demo.java的类。该类将包含您的主要方法

    使用默认构造函数创建类(对象)的实例。

    调用所有对象setter(mutator)方法为对象赋值

    调用对象显示方法,打印出它的值

    使用参数化构造函数

    创建类的另一个实例(另一个对象)

    调用对象显示方法,打印出它的值

    public class Shoes {
    
    
    //Instance Variables
    private String brand; 
    private int cost; 
    private double size; 
    
    
    // Default Constructor
        public Shoes(){
            brand = "";
            cost = 0;
            size = 0;
        }
    
    //Constructor
    public Shoes (String brand, int cost, double size)
    {
        this.brand = brand;
        this.cost = cost;
        this.size = size;
    }
    
    
    
    //Setter
    public void setBrand (String brand)
    {
        this.brand=brand;
    }
    
    public void setCost (int cost)
    {
        this.cost=cost;
    }
    
    public void setSize (double size)
    {
        this.size=size;
    }
    
    
    //Getter
    public String getBrand()
    {
        return brand;
    }
    
    public int getCost()
    {
        return cost;
    }
    
    public double getSize()
    {
        return size;
    }
    
    // Display data
    public void display()
    {
        System.out.println(brand);
        System.out.println(cost);
        System.out.println(size);
    
    }   
    

    }

    public class Demo {
    
    public static void main(String[] args) {
    
        // Create a object
                Shoes yeezys = new Shoes();
                Shoes kobes = new Shoes();
    
                yeezys.setBrand("Adidas");
                yeezys.setCost(200);
                yeezys.setSize(8.5);
                yeezys.display();
    
            System.out.println(""); 
    
        //Second object? Need help with this
                kobes.setBrand("Nike");
                kobes.setCost(150);
                kobes.setSize(9.5);
                kobes.display();
    
    }
    

    }

0 个答案:

没有答案