-1

I am very new with Java and now read book Shield complete reference 9th edition.

I wrote the next code:

class Area {

    double Area (double x, double y){
        double z;
        this.z = 5; // Problem 1
        return z = x*y;
    };

}

class ThisIsSparta {


    public static void main (String args []){


        double x = 10;
        double y = 5;
        double z = 0;
        Area result = new Area (x,y); //Problem 2
        z = result.Area(x, y);
        System.out.println("Test " + z);
    }
}

Problem 1: I could not understand purpose of "this", I thought that it is reference to object which had call class. So in my opinion I should return to main with z = 5. Instead i'am getting an error (compiler does not pass through it).

Problem 2: In a book example constructor was called with two arguments right during declaration, but in my case compiler do not allow to do it. Yes, I could do it in the next line, but I don't understand what is wrong.

khelwood
  • 55,782
  • 14
  • 81
  • 108
  • `double Area (double x, double y){` is not a constructor but method declaration (since it has return type). Methods shouldn't be named using class name (Area). While it is not compilation error, for our sanity we shouldn't do it since only constructors should use name of class. – Pshemo Feb 24 '19 at 19:16

1 Answers1

4

Problem 1 : this refers to the current object. In your case, it is an object of Area.

Read more: What is the meaning of "this" in Java?

Problem 2: You have not defined any constructor that takes two argument. double Area (double x, double y) is not the right signature for a constructor as it contains return type as double.

Read more on this here : Why do constructors not return values?

Turing85
  • 18,217
  • 7
  • 33
  • 58
Saurav Sahu
  • 13,038
  • 6
  • 64
  • 79