Question

In: Computer Science

1. Data in Java: Primitives and Objects In this section, we’ll build a class that is...

1. Data in Java: Primitives and Objects In this section, we’ll build a class that is composed of both primitives and objects. Java has classes to help in converting from primitives to objects (for example an int to an Integer) and vice-versa. Let’s start by building a small class used to represent a single concept such as a Car or Vehicle. Make a new Java project and and create a new class called “Car”. Cars should define primitives for things like odometers, etc., and Strings for make and model. Inside your Car class but outside of any method, define three (instance) variables for the odometer, make, and model. Write a main that builds 2 cars and prints them out. (Hint: Car c1 = new Car(); and System.out.println(c1.toString());.)

2. Variable Scope in Java: Local and Class-Level Lets practice building classes again and defining two variables: one local and one with class-level scope. Prove to yourself that you can access the class-level variable throughout the class in which it’s defined. Then, try to access the local variable from a method other than the one in which it’s defined. Finally, look inside of Rectangle.java and identify at least 4 instance variables (class-level) and at least 2 local variables. Indicate these using comments.

3. This (the Implicit Parameter) Take a class you’ve already built (or build the Car Class described in the “Data in Java” section) and build an object from that class. Observe the address of that object in main by using println with toString(). Next, from a method inside the class, print out the address of the “this” object using println. Call that method on the object you’ve just built, and explain why the two addresses are the same.

4. Access Modifiers: Public and Private Build yet another simple class (say, a Point or Pair). Then, create another (separate, distinct) class that is to be the “driver” for this example (just like the driver above). In your driver, build an object of the Point class and try to access a method declared as public. Now, on the same vehicle object, try to call a method declared as private. What message does Java print out? Next, declare some class-level data item as public (an int, say), and declare another class-level data item as private. In your driver’s “main”, try again to access these two data items – what message does the Java compiler display now?

5. Accessors and Mutators (or, Getters and Setters) Each of these sections encourages you to practice building small classes, and we’ll continue that pattern here. Construct a simple class used to store the time or date. Add a field for minute, second, and hour, but make these class-level variables private. So that our class can be used by external clients, we need to declare some public methods for use with our private data. Build two methods for each data item: one to get the value of the data item, and one to set the value of the data item. See the getters and setters defined in the Rectangle class for examples of these getters & setters.

6. Overriding toString() (and equals()) Build a simple class to represent a Vehicle (or reuse your Car class above). In a main, build an object of that class, and print out the object using System.out.println(). Notice that this simply reports the memory address of the object in question, and we’d like to do something more useful. To replace (or override) the toString (or equals) function, first see the examples defined in the NewAndReviewExamples.java file for both toString and equals. Now, build a toString function that prints out the make, model, and odometer reading for a vehicle object.

7. Overloading Methods Check out the Rectangle class constructors to see an example of overloading – defining multiple methods with the same name. Now build a SquareSomething class, with all static functions, whose purpose is to take an int, a double, or a float, and report back the square of the number (returning the correct type). This will mean your square class has three functions ( all named “square”) that each take a different type of data as input (int, double, float). Your square function that takes a double should return a double as well. This is how the println() method accomplishes such flexibility – you can hand it an int, a string, a double, a float, etc. and it simply prints the data. How it does so is by overloading the println() method to provide a different function for each possible type of input.

8. Constructors as Methods First, check out the set of constructors provided for you in the Rectangle class. Notice how they are overloaded (meaning many methods with the same name, but different with regards to input) to provide flexibility for users of this class. Add to your Car class two constructors – one to take a string make, the other to take two strings: a make and a model. Test these constructors by building multiple Cars in your main() driver, calling each constructor in turn.

Solutions

Expert Solution

Note: Could you plz go through this code and let me know if u need any changes in this.Thank You
_________________

1)

// Car.java

public class Car {
   //Declaring instance variables
   private int odometer;
   private String make;
   private String model;

   //Parameterized constructor
   public Car(int odometer, String make, String model) {
       this.odometer = odometer;
       this.make = make;
       this.model = model;
   }

   // getters and setters
   public int getOdometer() {
       return odometer;
   }

   public void setOdometer(int odometer) {
       this.odometer = odometer;
   }

   public String getMake() {
       return make;
   }

   public void setMake(String make) {
       this.make = make;
   }

   public String getModel() {
       return model;
   }

   public void setModel(String model) {
       this.model = model;
   }

   //toString method is used to display the contents of an object inside it
   @Override
   public String toString() {
       return "Odometer :" + odometer + ", Make :" + make + ", Model :"+ model;
   }

}
_________________________

// Test.java

public class Test {

   public static void main(String[] args) {
       //Creating an Car class object
Car car1=new Car(1500,"Honda","Civic");
//Displaying the Car class Object Info
System.out.println(car1);

   }

}
_________________________

Output:

Odometer :1500, Make :Honda, Model :Civic

_________________________

2)

// Rectangle.java

public class Rectangle {
//Declaring instance variables
private double width;
private double height;
private String color;
private String name;

//Parameterized constructor
public Rectangle(double width, double height, String color, String name) {
   this.width = width;
   this.height = height;
   this.color = color;
   this.name = name;
}


public void calcRectangleProps()
{
   double area,perimeter;
   area=width*height;
   perimeter=2*(width+height);
   System.out.println("Area of Rectangle :"+area);
   System.out.println("Periemter of Rectangle :"+perimeter);
  
}

//toString method is used to display the contents of an object inside it
@Override
public String toString() {
   // here we are accessing the class variables
   System.out.println("Rectangle :: Width=" + width + ", Height=" + height + ", Color="
           + color + ", name=" + name);
  
   //Trying to Access local variable of calcRectangleProps() method
   // System.out.println("Area of Rectangle :"+area);
   // System.out.println("Perimeter of Rectangle :"+perimeter);
  
   return "";
}

}
______________________________

3)

// Car.java

public class Car {
   //Declaring instance variables
   private int odometer;
   private String make;
   private String model;

   //Parameterized constructor
   public Car(int odometer, String make, String model) {
       this.odometer = odometer;
       this.make = make;
       this.model = model;
   }

   // getters and setters
   public int getOdometer() {
       return odometer;
   }

   public void setOdometer(int odometer) {
       this.odometer = odometer;
   }

   public String getMake() {
       return make;
   }

   public void setMake(String make) {
       this.make = make;
   }

   public String getModel() {
       return model;
   }

   public void setModel(String model) {
       this.model = model;
   }

   //toString method is used to display the contents of an object inside it
   @Override
   public String toString() {
       System.out.println(this.hashCode());
       return "Odometer :" + odometer + ", Make :" + make + ", Model :"+ model;
   }

}
____________________________

// TestCar.java

   public class TestCar {
  
       public static void main(String[] args) {
           //Creating an Car class object
   Car car1=new Car(1500,"Honda","Civic");
  
   //Displaying the Car class Object Info
   System.out.println(car1.hashCode());
   System.out.println(car1);
  
  
       }
  
   }
___________________________

Output:

366712642
366712642
Odometer :1500, Make :Honda, Model :Civic

____________________________

_____________________Thank You


Related Solutions

Give an example of how to build an array of objects of a super class with...
Give an example of how to build an array of objects of a super class with its subclass objects. As well as, use an enhanced for-loop to traverse through the array while calling a static method(superclass x). Finally, create a static method for the class that has the parent class reference variable.
java Objective: Create a class. Create objects. Use methods of a class. Create a class BankAccount...
java Objective: Create a class. Create objects. Use methods of a class. Create a class BankAccount to represent a bank account according to the following requirements: A bank account has three attributes: accountnumber, balance and customer name. Add a constructor without parameters. In the initialization of the attributes, set the number and the balance to zero and the customer name to an empty string. Add a constructor with three parameters to initialize all the attributes by specific values. Add a...
Create a generic method to print objects in java. Include a tester class.
Create a generic method to print objects in java. Include a tester class.
IN JAVA: Build a class called ExamPractice from scratch. This class should include a main method...
IN JAVA: Build a class called ExamPractice from scratch. This class should include a main method that does the following: Prompt the user to enter a number of inches Read the number of inches entered from the console Convert the inches into an equivalent number of miles, yards, feet, and inches. Output the results to the console. For example, if a user entered 100000 inches, the program would output: 100000 inches is equivalent to: Miles: 1 Yards: 1017 Feet: 2...
Learning Outcomes Using Java, maintain a collection of objects using an array. Construct a class that...
Learning Outcomes Using Java, maintain a collection of objects using an array. Construct a class that contains an array as a private instance variable. Construct methods with arrays as parameters and return values. Use partially filled arrays to implement a class where objects can be dynamically added. Implement searching and sorting algorithms. Instructions For this assignment you will be implementing an application that manages a music collection. The application will allow the user to add albums to the collection and...
Using Java Summary Create a Loan class, instantiate and write several Loan objects to a file,...
Using Java Summary Create a Loan class, instantiate and write several Loan objects to a file, read them back in, and format a report. Project Description You’ll read and write files containing objects of the Loan class. Here are the details of that class: Instance Variables: customer name (String) annual interest percentage (double) number of years (int) loan amount (double) loan date (String) monthly payment (double) total payments (double) Methods: getters for all instance variables setters for all instance variables...
Use LinkedList build-in class (java.util.LinkedList) to write a Java program that has: A. Method to print...
Use LinkedList build-in class (java.util.LinkedList) to write a Java program that has: A. Method to print all elements of a linked list in order. B. Method to print all elements of a linked list in reverse order. C. Method to print all elements of a linked list in order starting from specific position. D. Method to join two linked lists into the first list in the parameters. E. Method to clone a linked list. The copy list has to be...
Tissue Repair ( not in this chapter, we’ll cover in class)occurs in response to an injury,...
Tissue Repair ( not in this chapter, we’ll cover in class)occurs in response to an injury, often after an inflammatory and an immune response have happened. Outline – Unit 1, Chemistry, Cells, Tissues, Skeletal System Regeneration vs Fibrosis: Which one uses mitosis of the original cell types? Some types of tissues go through regeneration, others repair by fibrosis What are the consequences of fibrosis, for example, in heart muscle tissue? In Case of Emergency: Burns In 1st degree burns, only...
Create a Class with Data Fields and Methods in Java. Provide a Java coding solution for...
Create a Class with Data Fields and Methods in Java. Provide a Java coding solution for the following: 1. Name the class SalonServices 2. Add private data fields: a. salonServiceDescription – This field is a String type b. price - This field is a double type 3. Create two methods that will set the field values. a. The first method setSalonServiceDescription() accepts a String parameter defined as service and assigns it to the salonServiceDescription. The method is not static b....
Write a java program that creates a hashtable with 10 objects and 5 data members using...
Write a java program that creates a hashtable with 10 objects and 5 data members using mutator and accessor methods for each data member.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT