I have just started taking Java as a course in college and I am having a problem understanding how to find the syntax errors in a definition for a class.I am not asking for answers I just need help understanding it more.

The class is


public class AA
{

private int x;
private int y;

public void print()
{

System.out.println(x + " " +y);
}
public int sum ()
{
return x + y;

}

public AA ()
{
x = 0;
y = 0;
}

public int AA(int a, int b)
{

x = a;
y = b;

}
}

please help it is very urgent that i understand this.

Dani AI

Generated

A few simple syntax mistakes explain the compiler errors in 's class. The two root causes are: an extra closing brace that ends the class early (so the constructors appear outside the class body), and a constructor written with a return type so the compiler treats it as a regular method. was right to ask for compiler output — fix the first reported error and recompile, because later errors often cascade.

As noted, constructors must not declare a return type. Putting a type like int in front of what should be a constructor turns it into a method; if that method declares a non-void return type but has no return statement, it will fail to compile. The intended overloaded constructor should be declared without a return type, for example public AA(int a, int b), and it must be placed inside the class body.

Braces must be balanced and the class body must contain fields, constructors and methods before the final closing brace. The extra } before the constructors is the immediate problem: it closes the class, leaving the constructors and other members floating outside. Remove the stray brace, reformat or indent the file (or use an IDE with brace matching), then recompile. Fix the first error the compiler reports, then repeat until the file compiles.

's suggestion to add getters/setters is good design advice for encapsulation but does not affect the syntax errors. For authoritative guidance on constructors and correct form see the Java tutorial on constructors: Java Tutorials - Constructors.

Recommended Answers

All 3 Replies

Are you getting a syntax error? What is the error? We can't help you understand the errors if we don't know what they are.

Please post you code in code tags next time.

Are you trying to overload your constructor logic with public int AA(int a, int b)? If so you do not need the int as this specifies a return type. However, if you are not trying to overload the contstructor you need to return an integer from that method. alternativly change it to void, this may cause errors anyway due to having a method named the same as your class. Let me know the purpose of your final method please.

private variables >> need set and get methods

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.