Of the following, which would be considered the no-arg constructor for the rectangle class?

I tried to get this answered before but I couldn't get the code to work fully from what he gave me.

"

//Definition of class rectangle

public class Rectangle

{

//Declare required variables

private double w;

private double h;

//No-argument constructor

public Rectangle()

{

//Assign "w" to "1"

w = 1;

//Assign "h" to "1"

h = 1;

}

//Parameterized constructor

public Rectangle(double wid, double ht)

{

//Assign "wid" to "w"

this.w = wid;

//Assign "ht" to "w"

this.h = ht;

}

//Method definition for width

public double getWidth()

{

//Return width

return w;

}

//Method definition for height

public double getHeight()

{

//Return height

return h;

}

//Method definition for perimeter

public double getPerimeter()

{

//Return the perimeter

return 2.0*(w + h);

}

//Method definition for area

public double getArea()

{

//Return the area

return w*h;

}

}
//Definition of test class

public class Test

{

//Definition of main class

public static void main(String[] args)

{

//Create an object for rectangle class

Rectangle rect1 = new Rectangle(4, 40);

//Printing the area of rectangle

System.out.printf("The area of a 4.0 x 40.0 Rectangle is %.1f ", rect1.getArea());

//Printing the perimeter of rectangle

System.out.printf("The perimeter of a 4.0 x 40.0 Rectangle is %.1f ", rect1.getPerimeter());

//Create an object for rectangle class

Rectangle rect2 = new Rectangle(3.5, 35.9);

//Printing the area of rectangle

System.out.printf("The area of a 3.5 x 35.9.0 Rectangle is %.1f ", rect2.getArea());

//Printing the perimeter of rectangle

System.out.printf("The perimeter of a 3.5 x 35.9.0 Rectangle is %.1f ", rect2.getPerimeter());

}

}

"

When I put it in I get this error ( Rectangle.java:96: error: class Test is public, should be declared in a file named Test.java
public class Test )

I tried removing the public from the class it, and I don't get an error, but nothing gets output.

Of the following, which would be considered the no-arg constructor for the rectangle class?

In Unit 2, we learned how to create objects using constructor. Objects are created in programs by declaring a variable of the class and using the keyword new followed by a call to a constructor. Constructors set the initial values for the object’s instance variables. For example, here is how we create World, Turtle, and Person objects.

// To create a new object, write:
// ClassName variableName = new ConstructorName(arguments);
World world = new World();
Turtle t = new Turtle(world);
Person p = new Person("Pat","","123-456-7890");

In a new class, constructors are usually written after the instance variables and before any methods. They typically start with public and then the name of the class: public ClassName(). Unlike other methods, they do not have a return type, not even void, after the access modifier public. They can take parameters (specified in parentheses) for the data which is used to initialize the instance variables.

public class ClassName
{

   /* Instance Variable Declarations -- not shown */

   /* Constructor - same name as Class, no return type */
   public ClassName()
   {
     /* Implementation not shown */
   }
}

Note

Constructors must have the same name as the class! Constructors have no return type!

Classes usually have more than one constructor. There are usually at least 2 constructors:

  • a constructor that takes no parameters

  • a constructor that takes all the parameters necessary for initializing all the instance variables

The attributes of an object and their values at a given time define that object’s state. The constructors initialize the object’s state by assigning initial values to the instance variables that the object has as its attributes.

Here are two constructors that could be written for the Person class. Notice that the first one initializes name, email, and phoneNumber to empty string “” as the default values. Most programmers use “” as the default value for String variables and 0 as the default value for int and double variables.

// default constructor: initialize instance vars to default empty strings
public Person()
{
   name = "";
   email = "";
   phoneNumber = "";
}

// constructor: initialize all 3 instance variables to parameters
public Person(String initName, String initEmail, String initPhone)
{
   name = initName;
   email = initEmail;
   phoneNumber = initPhone;
}

If there are no constructors written for a class, Java provides a no-argument default constructor where the instance variables are set to their default values. For int and double variables, the default value used is 0, and for String and other object variables, the default is null. However, if you do write at least one constructor, Java will not generate the default constructor for you, so you should write at least a constructor with no parameters and one with many parameters.

Of the following, which would be considered the no-arg constructor for the rectangle class?
Check Your Understanding

5-2-1: Click on all the lines of code that are part of constructors in the following class.Constructors are public and have the same name as the class.

public class Name {

    private String first;
    private String last;

    public Name(String theFirst, String theLast) {
        first = theFirst;
        last = theLast;
     }

     public void setFirst(String theFirst) {
        first = theFirst;
     }

     public void setLast(String theLast) {
        last = theLast;
     }

}

    5-2-2: What best describes the purpose of a class’s constructor?

  • Determines the amount of space needed for an object and creates the object
  • The object is already created before the constructor is called but the constructor initializes the instance variables.
  • Names the new object
  • Constructors do not name the object.
  • Return to free storage all the memory used by this instance of the class.
  • Constructors do not free any memory. In Java the freeing of memory is done when the object is no longer referenced.
  • Initialize the instance variables in the object
  • A constructor initializes the instance variables to their default values or in the case of a parameterized constructor, to the values passed in to the constructor.

Of the following, which would be considered the no-arg constructor for the rectangle class?
Coding Exercise

The following class defines a Fraction with the instance variables numerator and denominator. It uses 2 constructors. Note that this constructor sets the default instance variable values to 1 rather than 0 – so we don’t end up with divide by zero. Try to guess what it will print before you run it. Hint! Remember to start with the main method! You can also view it in the Java visualizer by clicking on the Code Lens button below.

Of the following, which would be considered the no-arg constructor for the rectangle class?
Coding Exercise

The following class defines a Car with the instance variables model and year, for example a Honda 2010 car. However, some of the code is missing. Fill in the code for the 2 constructors that are numbered 1 and 2. And fill in the code to call the constructors in the main method numbered 3. The car1 object should test the first constructor with default values and the car2 object should test the second constructor to create a Honda 2010 car. Run your program and make sure it works and prints out the information for both cars.

Constructors are used to set the initial state of an object by initializing its instance variables. The examples above have instance variables that are primitive types, but you can have other objects, reference types, as instance variables. For example, a Person class could have an Address object as an instance variable, and the Address class could have String instance variables for the street, city, and state.

(Advanced AP Topic Warning) When you pass object references as parameters to constructors or methods, they become aliases for the original object and can change it. If a constructor has an object instance variable, it can copy the referenced object in the parameter using new and the constructor of the referenced object like below so that it does not change the state of the original object. You will see more examples like this in later lessons.

public class Person
{
  private String name;
  private Address addr; //Assumes an Address class is already defined

  // constructor: initialize instance variable and call Address constructor to make a copy
  public Person(String initName, Address initAddr)
  {
     name = initName;
     addr = new Address(initAddr.getStreet(),
                initAddr.getCity(), initAddr.getState());
  }
 }

5.2.1. Programming Challenge : Student Class¶

We encourage you to work in pairs for this challenge to create a Student class with constructors.

  1. First, brainstorm in pairs to do the Object-Oriented Design for a Student class. What data should we store about Students? Come up with at least 4 different instance variables. What are the data types for the instance variables?

  2. Write a Student class below that has your 4 instance variables and write at least 3 different constructors: one that has no parameters and initializes the instance variables to default values, one that has 4 parameters to set the instance variables, and one that has 1 parameter for the most important instance variable and uses defaults for the others.

  3. Add a print() method that uses System.out.println to print out all the instance variables.

  4. Add a main method that constructs at least 3 Student objects using the 3 different constructors and then calls their print() methods.

Create a class Student with 4 instance variables, 3 constructors, and a print method. Write a main method that creates 3 Student objects with the 3 different constructors and calls their print() method.

5.2.3. Summary¶

  • Constructors are used to set the initial state of an object, which includes initial values for all instance variables.

  • When no constructor is written, Java provides a no-argument default constructor, and the instance variables are set to their default values (0 for int and double, null for objects like String).

  • Constructor parameters are local variables to the constructor and provide data to initialize instance variables.

5.2.4. AP Practice¶

    5-2-7: Consider the definition of the Cat class below. The class uses the instance variable isSenior to indicate whether a cat is old enough to be considered a senior cat or not.

    public class Cat
    {
        private String name;
        private int age;
        private boolean isSenior;
        public Cat(String n, int a)
        {
            name = n;
            age = a;
            if (age >= 10)
            {
                isSenior = true;
            }
            else
            {
                isSenior = false;
            }
        }
    }
    

    Which of the following statements will create a Cat object that represents a cat that is considered a senior cat?

  • Cat c = new Cat (“Oliver”, 7);

  • The age 7 is less than 10, so this cat would not be considered a senior cat.

  • Cat c = new Cat (“Max”, “15”);

  • An integer should be passed in as the second parameter, not a string.

  • Cat c = new Cat (“Spots”, true);

  • An integer should be passed in as the second parameter, not a boolean.

  • Cat c = new Cat (“Whiskers”, 10);

  • Correct!

  • Cat c = new Cat (“Bella”, isSenior);

  • An integer should be passed in as the second parameter and isSenior would be undefined outside of the class.

    5-2-8: Consider the following class definition. Each object of the class Cat will store the cat’s name as name, the cat’s age as age, and the number of kittens the cat has as kittens. Which of the following code segments, found in a class other than Cat, can be used to create a cat that is 5 years old with no kittens?

    public class Cat
    {
        private String name;
        private int age;
        private int kittens;
    
        public Cat(String n, int a, int k)
        {
            name = n;
            age = a;
            kittens = k;
        }
        public Cat(String n, int a)
        {
            name = n;
            age = a;
            kittens = 0;
        }
        /* Other methods not shown */
    }
    
    I.   Cat c = new Cat("Sprinkles", 5, 0);
    II.  Cat c = new Cat("Lucy", 0, 5);
    III. Cat c = new Cat("Luna", 5);
    

  • I only
  • Option III can also create a correct Cat instance.
  • II only
  • Option II will create a cat that is 0 years old with 5 kittens.
  • III only
  • Option I can also create a correct Cat instance.
  • I and III only
  • Good job!
  • I, II and III
  • Option II will create a cat that is 0 years old with 5 kittens.

    5-2-9: Consider the following class definition.

    public class Cat
    {
        private String color;
        private boolean isHungry;
        /* missing constructor */
    }
    

    The following statement appears in a method in a class other than Cat. It is intended to create a new Cat object c with its attributes set to “black” and true. Which of the following can be used to replace missing constructor code in the class definition so that the object c below is correctly created?

    Cat c = new Cat("black", true);
    

  • public Cat(String c, boolean h)
    {
        c = "black";
        h = true;
    }
    

  • The constructor should be changing the instance variables, not the local variables.

  • public Cat(String c, boolean h)
    {
        c = "black";
        h = "true";
    }
    

  • The constructor should be changing the instance variables, not the local variables.

  • public Cat(String c, boolean h)
    {
        c = color;
        h = isHungry;
    }
    

  • The constructor should be changing the instance variables, not the local variables.

  • public Cat(String c, boolean h)
    {
        color = black;
        isHungry = true;
    }
    

  • The constructor should be using the local variables to set the instance variables.

  • public Cat(String c, boolean h)
    {
        color = c;
        isHungry = h;
    }
    

  • Correct!

You have attempted of activities on this page

When a method's return type is an object what is actually returned to the calling program?

When a method's return type is an object, what is actually returned to the calling program? only one copy of the field in memory.

What keyword in Java is the name of a reference that an object can use to refer to itself?

Within an instance method or a constructor, this is a reference to the current object — the object whose method or constructor is being called.

Which of the following should be used to create a variable that is shared by all instances of a class?

A static variable is shared by all instances of a class. Only one variable created for the class.

What is a method's signature quizlet?

A method signature consists of the method's name and the data types of the method's parameters, in the order that they appear. The return type is not part of the signature.