java - 如何在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);
}
}
解决方案
创建一个驱动程序类并调用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
}
}
推荐阅读
- pytorch - 将一维向量输入 Pytorch CNN
- .net - 如何防止 vb.net 应用程序滞后
- javascript - 试图将导航器道具传递给孙子时,获取“未定义不是对象”
- visual-studio-code - 当您点击重新聚焦窗口时,您可以阻止 VS Code 移动光标吗?
- java - 部署适配器时出现内容丢失错误“JAXRSApplicationClass”?
- java - Spark-线程 java.lang.NoSuchMethodError 中的异常
- java - 子类化时Java泛型不兼容的类型
- javascript - JavaScript 对作为数组的属性过滤对象
- oracle-apex - 如何处理用户名和密码页面项?
- python - 有人可以帮我分解并理解这个 collatz 序列代码吗?