In: Computer Science
I need this in Java please:
Lab11B: Understanding the constructor. Remember that the constructor is just a special method (with no return type) that has the same name as the class name. Its job is to initialize all of the attributes. You can actually have more than one constructor, so long as the parameters are different. Create a class called Turtle that has two attributes: 1) speed and 2) color. Then, create a constructor that has no parameters, setting the default speed to 0 and the color to “green”; this is called a default constructor. Next, create a second constructor that takes in two parameters. The second constructor should assign those parameters to the attributes. Then, in main, create two Turtle objects. For the first Turtle object, call the first constructor. For the second Turtle object, call the second constructor (passing it a speed of 5 and a color of “purple”). Using the dot ‘.’ Operator, print out the first turtle’s speed and the second turtle’s color. This is a test to see if you can design constructors inside your class and initialize attributes.
I have uploaded the Images of the code, Typed code and Output of the Code. I have provided explanation using comments (read them for better understanding).
Images of the Code:
Note: If the below code is missing indentation please refer
code Images
Typed Code:
// A class called Turtle
class Turtle
{
// An Integer class Attribute or variable named speed
int speed;
// An String class Attribute or variable named color
String color;
// default constructor : constructor without parameters
Turtle()
{
// setting default speed value to 0
speed=0;
// setting default color value to green
color = "green";
}
// second constructor : with input parameters spd and clr
Turtle(int spd,String clr)
{
// Assigning spd value to class variable speed
speed = spd;
// Assigning clr value to class variable color
color = clr;
}
}
public class Main
{
public static void main(String[] args)
{
// Creating two Turtle Objects
// Frist Turtle Object with default constructor
Turtle Turtle_1 = new
Turtle();
// Second Turtle Object with Second
constructor(parameterized constructor)
// with parameters speed 5 and
color purple
Turtle Turtle_2 = new
Turtle(5,"purple");
// Printing Turtle_1 Speed using
dot operator
System.out.println("Turtle 1 Speed:
"+ Turtle_1.speed);
// Printing Turtle_2 Color using
dot operator
System.out.println("Turtle 2 Color:
"+ Turtle_2.color);
}
}
//code ended here
Output:
If You Have Any Doubts. Please Ask Using Comments.
Have A Great Day!