如何输入同样是另一个类的对象的属性?

问题描述 投票:0回答:1

我有这门课xOy

    public class xOy {
        float x;
        float y;
        public void input(){  
           System.out.println("input infor");  
           Scanner sc = new Scanner(System.in);  
           this.x = sc.nextFloat();  
           this.y = sc.nextFloat();  
    }
}

还有另一个班级三角形

    public class Triangle extends xOy{  
        xOy point1;  
        xOy point2;  
        xOy point3;
    
}

我想让用户在控制台中输入 Triangle 类中每个点的 x 和 y 值。 我期望 point1.x = 3,point1.y = 5,与其他点类似。

java oop
1个回答
0
投票

这并不是真正的做法。您应该有一个构造函数来创建一个在创建时带有值的类,并有一个 setter 来将值分配给未初始化的类或更改该类的值。

import java.util.Scanner;

class XOy {
    private float x;
    private float y;
    
    public XOy() {}
    
    public XOy(float x, float y) {
        this.x = x;
        this.y = y;
    }
    public void setX(float x) {
        this.x = x;
    }
    public void setY(float y) {
        this.y = y;
    }
    public float getX() {
        return x;
    }
    public float getY() {
        return y;
    }
    @Override
    public String toString() {
        return "x = " + x + "y = " + y;
    }
}
      
class Triangle extends XOy {  
    public Triangle() {}
    public Triangle(float x, float y) {
        super(x,y);
    }
}
public class DemoConstructor {
    public static void main(String[] args) {
        Triangle t1 = new Triangle(10f,20f);
        System.out.println(t1.getX());
        System.out.println(t1.getY());
        
        // or
        Triangle t2 = new Triangle();
        Scanner s = new Scanner(System.in);
        System.out.println("Enter x and y");
        float x = s.nextFloat();
        float y = s.nextFloat();
        t2.setX(x);
        t2.setY(y);
        System.out.println(t2);
    }
}

输入和输出示例

10.0
20.0
Enter x and y
33
93
x = 33.0y = 93.0

© www.soinside.com 2019 - 2024. All rights reserved.