Search⌘ K
AI Features

Undefined Variables of a Class Type

Explore how to identify and correct the common error of using undefined variables of class types in Java. Learn the importance of initializing objects with the new operator and constructors to avoid compiler errors. This lesson helps you debug class-related mistakes by ensuring proper object creation before method invocation.

Two instances of the class Square

Let’s create two Square objects using the class Square given in the previous chapter. The following program attempts this task but includes a common mistake that anyone might make. Do you see the mistake?

Java
public class DemoTwoSquares
{
public static void main(String[] args)
{
Square smallSquare, bigSquare;
smallSquare.setSide(1);
bigSquare.setSide(100);
System.out.println("Small square: side = " +
smallSquare.getSide() + ", " +
"area = " + smallSquare.getArea());
System.out.println("Big square: side = " +
bigSquare.getSide() + ", " +
"area = " + bigSquare.getArea());
} // End main
} // End DemoTwoSquares

You ...