Question

In: Computer Science

write the program in java. Develop a class RentCabin that does the following: (use JavaDoc comments)...

write the program in java.

Develop a class RentCabin that does the following: (use JavaDoc comments)

// declare the constructor that sets the type and rate based in the sqft parm

       // set values based on sqft <1000 is small with $100 per night,

// sqft between 1000 and 2000, mid-sized $200 per night, and

// over 2000 as a large cabin with $300 per night

       //declare getRate

       //declare getType

       //declare setRate with int rate parm

       //declare setType with String type parm

       //declare computeRentalCost with int numDays parm

Create the RentCabinReflection test program: (40 points for code & 5 points for JavaDoc comments)

              // Obtain the class object if we know the name of the class

              Class rental = RentCabin.class

                     // get the absolute name of the class

                     // get the simple name of the class (without package info)

                     // get the package name of the class

                     // get all the constructors of the class

                     // initializing an object of the RentCabin class passing in 2001 sqft

                     // get all methods declared in the class

                     // but excludes inherited methods.

                     // get method with specific name and parameters

                     // call computeRentalCost method with parameter int 2 days

  

                     // get all the parameters of computeRentalCost

                     // get the return type of computeRentalCost

                     // gets all the public member fields of the class RentCabin

                           // get public field name

                           // get public field type

  

                           // get public field value

                     // How to access private member fields of the class

                     // getDeclaredField() returns the private field

                     // makes this private field instance accessible

                     // for reflection use only, not normal code

                     // get the value of this private field

  An explanation of the Java reflection example

Here is an explanation of the above code. Firstly, we obtain the class object of the class RentCabin. Then, we use some methods from the class java.lang.Class so as to obtain the perspective information from the class RentCabin. Afterwards, we retrieve the constructors of the class RentCabin and we instantiate an object with the integer 2001 as parameter. Also, we call two different methods for obtaining the methods provided by the class RentCabin. The difference between the methods getMethods() and getDeclaredMethods() is that the first one retrieves all the methods provided by class RentCabin including those methods inherited by the superclasses (in our case, this superclass is java.lang.Object), while the second one retrieves only the methods provided by our class.

Then, using the methods from the class java.lang.reflect.Method , we inspect information of the computeRentalCost() method.

Afterwards, using the methods from the class java.lang.reflect.Field , we retrieve information of the public member fields of the class RentCabin. In our case, only field int price is public.

Finally, we show a way to obtain information for private fields and for that purpose, we use the String type field which is private.

If we run the above code, we will have the following results: your rental must be for a large cabin for 2 days totaling $600)

Class Name is: RentCabin

Class Name without package is: RentCabin

Package Name is: null (if you do not have a package defined in the code)

Constructors are: [public RentCabin(int)]

Declared Methods are: [public java.lang.String RentCabin.getType(), public void RentCabin.setType(java.lang.String), public int RentCabin.getRate(), public void RentCabin.setRate(int), public void RentCabin.computeRentalCost(int)]

method = getType

method = setType

method = getRate

method = setRate

method = computeRentalCost

Method is: public void RentCabin.computeRentalCost(int)

The cost of your rental cabin is 600 USD

Parameter types of computeRentalCost() are: [int]

Return type is: void

Public Fields are:

Fieldname is: price

Type of field price is: int

Value of field price is: 600

One private Fieldname is: type

fieldValue = large

Solutions

Expert Solution

Java Code:

RentCabin.java

package rentcabin;

public class RentCabin {
    private int sqft;
    private int rate;
    private String type;

    public int price;

    /**
     * Sets the value of rate and type based on sqft param
     * 
     * @param sqft int
     */
    public RentCabin(int sqft) {
        this.sqft = sqft;

        if (sqft <= 1000) {
            this.rate = 100;
            this.type = "small";
        } else if (sqft > 1000 && sqft <= 2000) {
            this.rate = 200;
            this.type = "mid";
        } else {
            this.rate = 300;
            this.type = "large";
        }
    }

    /**
     * Returns the value of rate
     * 
     * @return rate int
     */
    public int getRate() {
        return this.rate;
    }

    /**
     * Returns the value of type
     * 
     * @return type String
     */
    public String getType() {
        return this.type;
    }

    /**
     * Sets the rate
     * 
     * @param rate int
     */
    public void setRate(int rate) {
        this.rate = rate;
    }

    /**
     * Sets the type
     * 
     * @param type String
     */
    public void setType(String type) {
        this.type = type;
    }

    /**
     * Compute the rental cost according to days
     * 
     * @param numDays int
     * @return int
     */
    public void computeRentalCost(int numDays) {
        this.price = numDays * this.rate;
        System.out.println("\nThe cost of your rental cabin is " + this.price + " USD");
    }
}

RentCabinReflection.java

package rentcabin;

import java.lang.reflect.*;

public class RentCabinReflection {
    public static void main(String[] args) throws NoSuchMethodException, SecurityException, IllegalArgumentException,
            IllegalAccessException, NoSuchFieldException {
        Class rental = RentCabin.class;

        // Absolute name of the class
        System.out.println("Class Name: " + rental.getName());

        // Simple name od the class
        System.out.println("Simple Class Name: " + rental.getSimpleName());

        // Package name of the class
        System.out.println("Package Name: " + rental.getPackageName());

        // Constructors of the class
        System.out.println("\nConstructors are: ");
        Constructor[] constructors = rental.getDeclaredConstructors();
        for (Constructor c : constructors) {
            System.out.println(c.getName());
        }

        // an object of RentCabin class
        RentCabin rc = new RentCabin(2001);

        // All Declared Methods in the class
        System.out.println("\nDeclared Methods are: ");
        Method[] methods = rental.getDeclaredMethods();
        for (Method m : methods) {
            System.out.println("method = " + m.getName());
        }

        // get method with specific name and parameters
        Method crc = rental.getMethod("computeRentalCost", int.class);
        System.out.println("\nMethod is = " + crc);

        // computeRentalCost method with parameter int 2 days
        rc.computeRentalCost(2);

        // Parameter types of computeRentalCost
        System.out.print("\nParameter types of computeRentalCost() are: ");
        Class[] parameters = crc.getParameterTypes();
        for (Class c : parameters) {
            System.out.println(c.getName());
        }

        // Return type of computeRentalCost
        System.out.println("Return type is: " + crc.getReturnType().getName());

        // All public member fields of class RentCabin
        System.out.println("\nPublic Fields are:");
        Field[] fields = rental.getFields();
        for (Field f : fields) {
            System.out.println("Fieldname is: " + f.getName());
            System.out.println("Type of field " + f.getName() + " is: " + f.getType());
            Object value = f.get(rc);
            System.out.println("Value of field " + f.getName() + " is: " + value);
        }

        // Access private fields
        Field f = rental.getDeclaredField("type");
        f.setAccessible(true);
        System.out.println("\nOne private field name is: " + f.getName());
        Object value = f.get(rc);
        System.out.println("fieldValue: " + value);
    }
}

Output:

Code Screenshots:

RentCabinReflection.java


Related Solutions

write program that develop a Java class Dictionary to support the following public methods of an...
write program that develop a Java class Dictionary to support the following public methods of an abstract data type: public class Dictionary { // insert a (key, value) pair into the Dictionary, key value must be unique, the value is associated with the key; only the last value inserted for a key will be kept public void insert(String key, String value); // return the value associated with the key value public String lookup(String key); // delete the (key, value) pair...
Write a program in java that does the following: Create a StudentRecord class that keeps the...
Write a program in java that does the following: Create a StudentRecord class that keeps the following information for a student: first name (String), last name (String), and balance (integer). Provide proper constructor, setter and getter methods. Read the student information (one student per line) from the input file “csc272input.txt”. The information in the file is listed below. You can use it to generate the input file yourself, or use the original input file that is available alone with this...
Write a program in java processing. Write a program that does the following: · Assume the...
Write a program in java processing. Write a program that does the following: · Assume the canvas size of 500X500. · The program asks the user to enter a 3 digit number. · The program then checks the value of the first and last digit of the number. · If the first and last digits are even, it makes the background green and displays the three digit number at the mouse pointer. · If the two digits are odd, it...
Write a java program with the following classes: Class Player Method Explanation: play : will use...
Write a java program with the following classes: Class Player Method Explanation: play : will use a loop to generate a series of random numbers and add them to a total, which will be assigned to the variable score. decideRank: will set the instance variable rank to “Level 1”, “Level 2”, “Level 3”, “Level 4” based on the value of score, and return that string. getScore : will return score. toString: will return a string of name, score and rank....
Write a complete Java program, including comments in each method and in the main program, to...
Write a complete Java program, including comments in each method and in the main program, to do the following: Outline: The main program will read in a group of three integer values which represent a student's SAT scores. The main program will call a method to determine if these three scores are all valid--valid means in the range from 200 to 800, including both end points, and is a multiple of 10 (ends in a 0). If the scores are...
Write a complete Java program, including comments in each method and in the main program, to...
Write a complete Java program, including comments in each method and in the main program, to do the following: Outline: The main program will read in a group of three int||eger values which represent a student's SAT scores. The main program will call a method to determine if these three scores are all valid--valid means in the range from 200 to 800, including both end points, and is a multiple of 10 (ends in a 0). If the scores are...
Please use Java language with comments! Thanks! Write a program that will display multiple dots move...
Please use Java language with comments! Thanks! Write a program that will display multiple dots move across the Frame and randomly change direction when they hit the edge of the screen. Do this by creating a Dot class and making each dot an object of that class. You may reuse code written in class for this part of the assignment. Create a subclass of the Dot class called PlayerDot that is controlled by the player through keyboard input (arrow keys)...
Write a complete Java program, including comments in both the main program and in each method,...
Write a complete Java program, including comments in both the main program and in each method, which will do the following: 0. The main program starts by calling a method named introduction which prints out a description of what the program will do. This method is called just once.      This method is not sent any parameters, and it does not return a value. The method should print your name. Then it prints several lines of output explaining what the...
Write a complete Java program, including comments in both the main program and in each method,...
Write a complete Java program, including comments in both the main program and in each method, which will do the following: 0. The main program starts by calling a method named introduction which prints out a description of what the program will do. This method is called just once.      This method is not sent any parameters, and it does not return a value. The method should print your name. Then it prints several lines of output explaining what the...
Write a complete Java program, including comments in both the main program and in each method,...
Write a complete Java program, including comments in both the main program and in each method, which will do the following: 0. The main program starts by calling a method named introduction which prints out a description of what the program will do. This method is called just once.      This method is not sent any parameters, and it does not return a value. The method should print your name. Then it prints several lines of output explaining what the...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT