简体   繁体   中英

How to pass parameter from one to another class in Java?

I want to pass coordinates of Point to Shape addPoint(). and store these coordinates to the linked list first 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);
    }
}

second class - Shape here I tried to use function in order to add coordinates of this point to the linked list but I dont know, is it right or not? I need somehow pass these coordinates in this class but don't know how to code it.

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

Create a driver class and call addPoint as below,

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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