w3resource

Creating a Java Cat Class with Default Constructor


Default Constructor:
Write a Java program to create a class called “Cat” with instance variables name and age. Implement a default constructor that initializes the name to "Unknown" and the age to 0. Print the values of the variables.

Sample Solution:

Java Code:

Cat.java

// Define the Cat class
public class Cat {
    // Private instance variables
    private String name;
    private int age;
    // Default constructor
    public Cat() {
        // Initialize name to "Unknown"
        this.name = "Unknown";
        // Initialize age to 0
        this.age = 0;
    }
    // Getter for name
    public String getName() {
        return name;
    }
    // Getter for age
    public int getAge() {
        return age;
    }
    // Main method to test the Cat class
    public static void main(String[] args) {
        // Create a new Cat object using the default constructor
        Cat myCat = new Cat();
        // Use the getter methods to access private variables
        System.out.println("Cat's Name: " + myCat.getName());
        System.out.println("Cat's Age: " + myCat.getAge());
    }
}

Output:

Cat's Name: Unknown
Cat's Age: 0

Explanation:

  • Define the Cat class:
    • The Cat class is defined with the keyword class.
  • Private instance variables:
    • The Cat class has two private instance variables: name (a String) and age (an int).
  • Default constructor:
    • The default constructor Cat() is defined.
    • Inside the default constructor, name is initialized to "Unknown".
    • age is initialized to 0.
  • Main method:
    • The main method is defined to test the Cat class.
    • A new Cat object (myCat) is created using the default constructor.
    • The values of the instance variables (name and age) are printed to the consol

Note on Constructors:

In the above exercise, the default constructor for the Cat class works by:

  • Initialization: When a new Cat object is created, the default constructor is called automatically.
  • Setting Default Values: The constructor initializes the name to "Unknown" and the age to 0, ensuring that these variables have default values when an object is created without specific values provided.
  • Encapsulation: By keeping the instance variables private and initializing them through the constructor, the class ensures that the variables are always set to a known state when an object is created.

Java Code Editor:

Improve this sample solution and post your code through Disqus.

Java Constructor Previous: Java Constructor Exercises Home.
Java Constructor Next: Creating a Java Dog Class with Parameterized Constructor.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.