Skip to content

Instantly share code, notes, and snippets.

@wingleungchoi
Created May 6, 2019 14:22
Show Gist options
  • Save wingleungchoi/7b69a3822e70d8a43b21f61082a38b0f to your computer and use it in GitHub Desktop.
Save wingleungchoi/7b69a3822e70d8a43b21f61082a38b0f to your computer and use it in GitHub Desktop.
Dog Java Example
public class Dog {
// Attributes [i.e. data]
private String name;
// Behavior [i.e. methods]
// Constructors
public Dog() //constructor which takes no parameters, sets to default
{
name="";
}
// fully parameterized constructor
public Dog(String name)
{
this.name=name;
}
// copy constructor
public Dog(Dog someDog)
{
this.name=someDog.getName();
}
public static void bark(String reason)
{
System.out.println("Bark for" + reason);
}
// other behavior (non-constructor behavior)
public String getName() {
return name;
}
public void setName(String newName) {
name = newName;
}
public static void main(String []args) {
Dog myDog = new Dog( "nathan");
myDog.setName( "nathan II" );
/* Call another class method to get Dog's Name */
String myDogName = myDog.getName();
/* You can access instance variable as follows as well */
System.out.println("myDogName: " + myDogName );
Dog clonedDog = new Dog(myDog);
/* You can access instance variable as follows as well */
System.out.println("cloned dog name: " + clonedDog.getName() );
}
} // end class
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment