-4

so in this code we have three methods and I dont understand why we use voids in two of the methods and dont in one can someone explain with detail

class Point {

private double anan;
private double baban;

public void print(){
    System.out.println("(" + anan + "," + baban + ")");


}
public Point(double anan, double baban) {
    this.anan = anan;
    this.baban = baban;


}

public void scale(){
    anan = anan/2;
    baban = baban/2;

}
Unknown
  • 13
  • 2

2 Answers2

1

Constructor dont have returntype

public Point(double anan, double baban) {}  // is a constructor
public void print(){}   // is a method
public void scale(){}   // is a method

From the Providing Constructors for Your Classes , Deifining Methods

Constructor declarations look like method declarations—except that they use the name of the class and have no return type

The only required elements of a method declaration are the method's return type, name, a pair of parentheses, (), and a body between braces, {}.

The return type—the data type of the value returned by the method, or void if the method does not return a value.

singhakash
  • 7,891
  • 6
  • 31
  • 65
1

When a method does not return something then return type should be void.

As your method Point()

public Point(double anan, double baban) {
    this.anan = anan;
    this.baban = baban;
}

is the constructor method, so there has no return type.

Here is a discussion about Methods vs Constructors

The important difference between constructors and methods is that constructors create and initialize objects that don't exist yet, while methods perform operations on objects that already exist.

Constructors can't be called directly; they are called implicitly when the new keyword creates an object. Methods can be called directly on an object that has already been created with new.

The definitions of constructors and methods look similar in code. They can take parameters, they can have modifiers (e.g. public), and they have method bodies in braces.

Constructors must be named with the same name as the class name. They can't return anything, even void (the object itself is the implicit return).

Methods must be declared to return something, although it can be void.

For further reading see methods and constructors.

Community
  • 1
  • 1
ashiquzzaman33
  • 5,781
  • 5
  • 31
  • 42