how to call a method from one class to a method from another class


The question is this, I have to calculate the perimeter of a triangle but I need to call the method calcularDistancia of class Punto a class Triangulo in the method calcularPerimetro or in simple terms put a method inside another method .

import java.awt.Graphics;

public class Punto {

private int x;
private int y;

public String toString() {
    return "X=" + x +"\n"
           +"Y=" + y + "";

public Punto(int x, int y) {
    this.x = x;
    this.y = y;

public int getX() {
    return x;

public int getY() {
    return y;
public void mostrar() {

public double calcularDistancia(Punto pb) {
    double dis=Math.sqrt(Math.pow(x-pb.getX(),2))
    return dis;

public class Triangulo {

private Punto puntoAX,pAY;
private Punto  puntoBX,pBY;
private Punto puntoCX,pCY;

public Triangulo(int puntoAX, int pAY, int puntoBX, int pBY, int puntoC, int pCY) {
    this.puntoAX = new Punto(puntoAX,pAY);
    this.puntoBX =new Punto(puntoBX,pBY);
    this.puntoCX = new Punto(puntoC,pCY);

public String toString() {
    return "Estado del tirangulo\n "
            +"\nPunto A\n"+
            "\nPunto B\n"+
            "\nPunto C\n"+

public void mostrarEstado() {

public double calcularPerimetro() {
    return 0;


asked by juanito 09.05.2018 в 03:19

3 answers


If I did not get it wrong, to call the function calcularDistancia of Punto from any method of the class Triangulo it would suffice to instantiate an object of type Punto

For example;

public double calcularPerimetro() {
    Punto punto = new Punto(2,3);
    double aux = punto.calcularDistancia(punto);
    //Aquí ya se podrías trabajar tranquilamente con el retorno de calcularDistancia
    return aux;

I hope you find it useful, greetings

answered by 09.05.2018 / 06:33

I understand that your Point class contains a method to calculate the distance to another (or the same) instance of Point, that is, the distance between a given point and any other, of this then, in the method of calculating your level. Triangle class, having already the instances of the points then you do not have to do more than add the distances between each of them, it would be something like that if I'm not wrong:

public double calcularPerimetro() {
    return this.puntoAX.calcularDistancia(this.puntoBX)
    + this.puntoBX.calcularDistancia(this.puntoCX)
    + this.puntoCX.calcularDistancia(this.puntoAX);
answered by 09.05.2018 в 19:49

I do not know how to do it in java, but in .net it works in the following way, so you can guide yourself and find a similar way in java.

public int suma (int a) {   return a + 4; } public int CallMetodo (fun Metodoentrada) {  int result = Input Method (4);  return result; }

When you call the method CallMethod, the result will be 8. I hope it helps you, for now I'll look for a form in java and I'll tell you.

answered by 09.05.2018 в 04:41