繁体   English   中英

如何在 Java 中将参数从一个传递到另一个 class?

[英]How to pass parameter from one to another class in Java?

我想将点的坐标传递给形状 addPoint()。 并将这些坐标首先存储到链表 class - Point find distance between two points


package com.company;
import java.lang.Math;
import java.util.Scanner;

public class Point {
    //fields
    public int x; //coordinate of point
    public int y;

    //constructor
    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }

    //method
        //getters
    public int getX() {
        return x;
    }
    public int getY() {
        return y;
    }
        //setters
    public void setX(int x) {
        this.x = x;
    }
    public void setY(int y) {
        this.y = y;
    }

    //function distance
    public void distance(Point point) {
        double res = Math.sqrt(
                Math.pow(getX() - point.getX(), 2) +
                        Math.pow(getY() - point.getY(), 2)
        );
        System.out.println(res);
    }
}

第二个 class - Shape here 我尝试使用 function 来将此点的坐标添加到链表中,但我不知道,对吗? 我需要以某种方式在这个 class 中传递这些坐标,但不知道如何编码。

package com.company;
import java.util.*;

public class Shape {

    public void addPoint(Point receivedPoint) {
        // Creating object of class linked list
        LinkedList<Point> points = new LinkedList<Point>();
        // Adding elements to the linked list
        points.add(receivedPoint);
        points.add(receivedPoint);
        System.out.println("Linked list : " + points);
    }
}

创建一个驱动程序 class 并调用addPoint如下,

public class Driver {
    public static void main(String[] args) {
        Point point = new Point(10,20); //create point object
        Shape shape = new Shape();
        shape.addPoint(point); //call method
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM