-1
class Person {
private String name;
private int age;

Person() {
    this.name = "";
    this.age = 0;
}

Person(String name, int age) {
    this.name = name;
    this.age = age;
}

void getName(String name) {

}
}

I am new to Java and was practicing making objects. In the code above I created a Person object with two overloaded constructors. I hope those are correct. I tried making a method without specifying that returns void and got an error. Do methods inside of objects always require a return type? I'm not sure why the IDE gave me an error when I didn't specify it as void.

*edit I realized I never actually created the Person object, only the Person class.

AvP
  • 359
  • 2
  • 3
  • 14

3 Answers3

2

All methods require a return type, or void, as part of their signature. void indicates that you are not returning anything, or if the return keyword is used, it is not followed by any value.

Constructors are special - they are not defined with a return type, as they always return the object they are instantiating and they are always named the same as the class name.

Makoto
  • 104,088
  • 27
  • 192
  • 230
  • So what I have done for my getName() method was correct? I just have to specify the return type of each method inside an object. – AvP Dec 11 '13 at 04:51
  • I see nothing syntatically wrong with your method. Sure, there's no method *body*, but that's still syntatically correct...If this were a conventional getter, however, its return type would be the same as the field you're returning (in this case, `String`), and it would accept no arguments. – Makoto Dec 11 '13 at 04:52
1
public class Person {
private String name;
private int age;

public Person() 
{
this.name = "";
this.age = 0;
}

public Person(String name, int age) {
this.name = name;
this.age = age;
}

public static Person GetObect() 
{
    return new Person("Steven N",22);


}
public void ShowDetails()
{
System.Out.Println("Name "+this.name+" and age is "+this.age);

}

}
class TestObject
{
public static void main(string arg[])
{
Person ob=Person.GetObject();
ob.ShowDetails();
}

}

Hope this will help you.

Muhammad Essa
  • 142
  • 1
  • 10
0

where is the person object you created,there are only 2 constructor, one method and a class Person.Object are created like this way Person p =new Person(); All methods must have a return type like void or int or String or anything that extends Object class but constructor do not have any return type As you are new to java see this link to know the different ways of creating objects

Community
  • 1
  • 1
SpringLearner
  • 13,738
  • 20
  • 78
  • 116