Basics of classes and objects: Java

Dhruv Garg :

The question that I received:

Define a class hotel with the following specifications:

Private members:

Roomno            
Name
Charges_day     
No_of_days     

Public members:

Getit()      -to enter the data members
Showit()  to show the data member
Compute()   -To calculate and return the total charges as charges_day * No_of_days

and a constructor function to initialize the data members.


The code I wrote:

public class hotel{
    private int Roomno;
    private String Name; 
    private int Charges_day; 
    private int No_of_days;

    public hotel(){
        Roomno = 0; 
        Name = "";
        Charges_day = 0;
        No_of_days = 0; 
    }

    public void Getit(int r, String n, int c, int no){
        Roomno = r; 
        Name = n;
        Charges_day = c;
        No_of_days = no;
    }

    public String Showname(){
        return Name;
    }
    public int  Showit(){
        return Roomno;
        return Charges_day;
        return No_of_days;
    }

    public int Compute(){
        return (Charges_day*No_of_days); 
    }

}

I am aware that I can't have more than 1 returns in one method function, but I'm unable to find a way around this.

azro :

Regarding the requirement, I'd suggest you just print the values

public void Showit(){
    System.out.println(Name+" "+Roomno+" "+Charges_day+" "+No_of_days);
}

If you need a method that return a String representation of your object, override toString()

public String toString(){
    return Name + " " + Roomno + " " + Charges_day + " " + No_of_days;
}

Also Java convention for naming is

  • lowerCamelCase for methods and attributs

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=477460&siteId=1