Skip to content

Instantly share code, notes, and snippets.

@sprejjs
Last active July 8, 2017 00:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sprejjs/89bb6d5c1f39f5abbca99ec635dde043 to your computer and use it in GitHub Desktop.
Save sprejjs/89bb6d5c1f39f5abbca99ec635dde043 to your computer and use it in GitHub Desktop.
Custom model class example
package com.company;
//Name of the class
public class Cat {
//Private variables
private int age;
private String name;
//Private constant
private final boolean isMale;
//Constructor
public Cat(int age, String name, boolean isMale) {
this.age = age;
this.name = name;
this.isMale = isMale;
}
//Accessors (a.k.a. getters)
public int getAge() {
return age;
}
public String getName() {
return name;
}
public boolean isMale() {
return isMale;
}
//Modifiers (a.k.a. setters)
/**
* Sets the age for the current cat
*
* @param age an integer with the valid values between 0 and 25
* @return true if value has been assigned and false if the parameter is invalid
*/
public boolean setAge(int age) {
//Validate your parameters, valid age for a cat is between 0 and 25 years
if (age > 0 && age < 25) {
this.age = age;
return true;
}
return false;
}
public void setName(String name) {
this.name = name;
}
//We cannot provide a setter for a constant, it has to be specified through a constructor
//@toString method allows you to print information about the current object.
@Override
public String toString() {
String gender = "Female";
if (isMale) {
gender = "Male";
}
return String.format("Name: %s\nAge: %s\nGender: %s", name, age, gender);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment