Lesson 4: Object-Oriented Programming
Activity 12: Creating a Simple Class in Java
Solution:
- Create a new project in the IDE named Animals.
- In the project, create a new file named Animal.java under the src/ folder.
- Open Animal.java and paste in the following code:
public class Animal {
}
- Inside the curly braces, create the following instance variables to hold our data, as shown here:
public class Animal {
int legs;
int ears;
int eyes;
String family;
String name;
}
- Below the instance variables, define two constructors. One will take no arguments and initialize legs to 4, ears to 2, and eyes to 2. The second constructor will take the value of legs, ears, and eyes as arguments and set those values:
public class Animal {
int legs;
int ears;
int eyes;
String family;
String name;
public Animal(){
this(4, 2,2);
}
public Animal(int legs, int ears, int eyes){
this...