Java vs Ruby Class – A Syntax Comparison

The objective of this article is to compare the structure of  a class in Java and Ruby. I believe this will help Java or Ruby developers to compare one another.

As an example let us consider a simple Employee class with three attributes – first name, last name , email and city.

Java Version

[code]

public class Employee {

private String firstName;
private String lastName;
private String email;
private String city;

public Employee(String firstName, String lastName,
String email, String city) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
this.city = city;
}

public String getFirstName() {
return firstName;
}

public void setFirstName(String firstName) {
this.firstName = firstName;
}

public String getLastName() {
return lastName;
}

public void setLastName(String lastName) {
this.lastName = lastName;
}

public String getEmail() {
return email;
}

public void setEmail(String email) {
this.email = email;
}

public String getCity() {
return city;
}

public void setCity(String city) {
this.city = city;
}</pre>
public String toString() {

return lastName +" , " + firstName;

}
<pre>
}

[/code]

Ruby Version

[code]

class Employee

def initialize (firstName, lastName, email, city)

@firstName = firstName
@lastName = lastName
@email = email
@city = city

end

def getFirstName()
return firstName
end

def setFirstName(firstName)
@firstName=firstName;
end

def getLastName()
return lastName;
end

def setLastName(lastName)
@lastName = lastName;
end

def getEmail()
return email;
end

def setEmail(email)
this.email = email;
end

def getCity()
return city;
end

def setCity( city)
this.city = city;
end

</pre>
def to_s()
s = "[" + @firstName +", " + @lastName +" ]"
end
<pre>end

[/code]

However there are provisions in Ruby to express the get / set methods.

Posted in: Programming

Leave a Comment