首页 > 解决方案 > 如何在Java中将参数从一个类传递给另一个类?

问题描述

我想将点的坐标传递给形状 addPoint()。并将这些坐标存储到链表 第一类 - 点 查找两点之间的距离


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);
    }
}

第二类-形状 在这里我尝试使用函数来将此点的坐标添加到链表中,但我不知道,是否正确?我需要以某种方式在此类中传递这些坐标,但不知道如何编码。

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);
    }
}

标签: javaclassmathparameters

解决方案


创建一个驱动程序类并调用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
    }
}

推荐阅读