I've been given a coursework assignment where I have to build a prototype hotel booking system, in accordance with the specification, which is as follows:
You will need at least three classes:
Hotel
This should store all the essential information about a hotel,
including a name and some rooms.
Room
This should store the number of beds in a room.
Bed
This should store the size of a bed (i.e. single or double).
I'm totally confused about where to start!
I was under the impression that objects could not be contained within other objects.
For example, let's assume we instantiate a "Hotel" object. How would we then instantiate "Room" objects, and within that object, "Bed" objects?
How are these objects being stored? How do we interact with them indirectly, from another object?
Typically you don't need to nest classes into other classes, which are called inner classes, unless the work that a class takes care of can be chunked into small units that never need to be known outside it's parent class.
It sounds like the concept you want to look into is Composition. It's when an object holds a reference to another object.
public class Room {
private boolean isVacant;
public Room() {
isVacant = true; // The room starts vacant
}
// Pretend there is a way for clients to check in and out of the room
public boolean isVacant() {
return isVacant;
}
}
public class Hotel {
// Using composition, I can make an instance of one class
// available to the methods of another
private Room room101;
public Hotel(Room room101) {
this.room101 = room101;
}
public boolean isRoom101Vacant() {
return room101.isVacant();
}
}
Our hotel may not be very useful having only one room, but this example shows how you can "compose" one object into another. Methods of Hotel can now use methods of it's Room instance known as room101. You will want to think about how your rooms are structured, and how you want to represent it within your Hotel class. A few objects used to store collections of other objects include ArrayList and HashMap.
Edit:
this is a fairly difficult concept to understand before you understand what a class is compared to an instance of that class (an object). In the constructor of my sample Hotel class, I have a variable of type Room called room101. And outside of the constructor is an instance field of the same type and name.
Java will always refer to a variable or reference of the nearest scope. So if I have a method reference called room101, how can I refer to that other one declared outside the constructor, at instance level? That's where this comes in.
public class ThisExample {
// This is a separate variable at the instance level
// Lets call this global in the comments
private int a;
public ThisExample() {
// This is a separate variable in the method level,
// lets call this local in the comments
int a;
a = 5; // our local is now assigned 5
this.a = 10; // Our global is now assigned 10
this.a = a; // our global is now assigned to 5
a = this.a * 2; // our local is now assigned to 10
}
}
In short, this refers to "this" instance of a class. It's a way for an instance of a class to refer to itself as if from the outside. Just like how another object would refer to room101's method as room101.isVacant(). A method in the Room class would similarly do this.isVacant() for the same effect.
And as a final note, if there is only one declaration of a symbol within a class. The this keyword is implied. So Room can call it's own method just as well without it as long as there is no other conflicting symbols of the same name. (This doesn't occur with methods as much as with instance fields/local variables)
Hopefully this helps clear things up a bit!
Your assignment is how to model some real world concepts into code.
It appears that the core of your problem can be stated as a Guest can book a Room.
I don't want to do your work for you, so let me start by asking how you would write that in code? After that, we can address the "Hotel" and "Bed". Is this a major assignment or just a quick question? Your implementation would depend on this.
A rule to learn and apply is:
An action on an object in the real world, becomes a method of that object in an Object Oriented approach.
Related
What happens when we create an instance of a class? I mean, will every field and method of that class be inside that object (with allocated memory) or will it not have anything inside and have a reference to its class, instead. (First option looks like a waste of memory.)
Whenever a new object is created, new memory is allocated in the heap space (dynamic memory). This space is reserved for everything that's specific to this single instance of a class. That means every field (instance field, not the static one) would have its own separate location in memory.
For methods, things are different since they are common for all instances of a class, which means you would have one method in memory which would be referred to by each instance of a class.
If you wonder where are local variables of a method stored: they are stored on the stack, meaning they are not shared between invocations of that method.
Also, methods are stored in the 'code memory', separate from instance fields.
The full concept of OOP (Object Oriented Programming) is being able to abstract the reality by "describing" the objects.
To accomplish this purpose we're able to declare an object attributes, for example.
You can have an object Person, this person has different attributes, such as name, age, address. Also you can describe the different actions of this person, such as eating, taking a bath, etc. The abstraction of this would look like:
class Person(){
int age;
String name;
String address;
void eating(){
//describe the process of eating
}
void takeBath(){
//describe the process of taking a bath
}
}
The whole purpose of this is that afterwards you can instantiate an Object Person and it will have all of it's attributes.
You can call the object in another class and instantiate it, this call will look like:
Person person1 = new Person(); //here you are saying that you have a new variable of type person
person1.name = "Eduardo"; //You're saying that his name is Eduardo
person1.age= 28; //he is 28 years old
person1.eating(); //he's eating, I like to eat tho.
Person person2 = new Person(); //You are saying that there's another person
person2.name = "Maria"; //her name is Maria
person2.age = 31; //She's 31 years old
person2.takeBath(); She's taking a bath
As you can see I didn't have to declare again the methods or attributes of the class, simply created a new object and started setting the attributes (please be aware of the difference between declaring and setting, to declare is to say there is an attribute of X type; setting is giving a value to that attribute).
There's another very useful property in OOP called heritage. Lets say we want to describe a Programmer; a programmer is a Person and he can do whatever a person does but also he codes and has a preferred language this would look like:
class Programmer extends Person { // I'm declaring the class but also I'm saying it's a person, so it will have all the attributes and methods of the Person class.
String preferredLanguage; //I will only declare the new attribute that is preferred Language, name, age and address are set because it's a person
void code(){
//the process of making very awesome things
}
}
And then I can instantiate another object Programmer
Programmer person3 = new Programmer(); //I called it person3 so you can understand it's only a variable, you can call it as you wish.
person3.name = "Berkay"; //Set the name without the need of declaring it in the method programmer, it's been inherit by the class Person
person3.code();//it can code!
person3.takeBath(); //A method of Person
person3.code(); //method of Programmer
At this stage I'd like to point that Programmer having the attributes of Person doesn't mean the same way around. For example, trying to make this would be a mistake:
person1.code(); //person1 is a Person and it doesn't have the code method.
PS: There are a lot of things to improve in these code, it's far from using best practices. All I intend to do is to give a clear example of the way OOP works. I didn't test the code, it's only illustrative, it may contain typos
I don't get it for long. Are there any alternative words similar to 'instance' that are easier to understand? For a non-programmer, how you explain instance? Instance is like example in normal person's world. I can't understand what it is if I don't even understand its meaning.
"instance" is best understood as it relates to "class" in programming. "Classes" are used to define the properties and behavior of a category of things. E.g. A "Car" class might dictate that all cars be defined by their make, model, year, and mileage.
But you can't provide specifics about a particular car (for example, that 1978 Chevy Impala with 205,000 miles on it that your uncle Mickey drives) until you create an "instance" of a Car. It's the instance that captures the detailed information about one particular Car.
To understand what an instance is, we must first understand what a class is.
A class is simply a modeling tool provided by a programming language for use in representing real world objects in a program or application.
The class is structured to accommodate an object's properties (member variables) and its operations (member functions/methods).
An Instance on the other hand is simply a variation of an object created from a class. You create an object variant (Instance) using a constructor which is a method within a class specifically defined for this purpose.
Consider a Car, if you wanted to represent it in your application you would define a class identified as Car which contains the properties of the car and the
operations that the car can perform.
It would look something close to this, supposing it was done in Java programming language:-
public class Car{
//the properties of the car
private String make;
private int year;
private int gear;
private int speed;
...
//constructor used to create instances of the car
public Car(String carMake, int yearManf){
year = yearManf;
make = carMake;
}
//Car Operation/methods
public void setGear(int gearValue){
gear = gearValue
}
public void applyBrake(int decrement){
speed -= decrement;
}
public void accelerate(int increment){
speed += increment;
}
...
}
Create an instance of a car:-
Car BMW = new Car("385 i", 2010);
BMW here is an instance of a car.
Going outside the world of programming for a second: you know what people are. You are an "instance" of the class "people" - I can talk about people in general (the class of objects), or if I have a specific one in mind, I talk of an "instance". An instance can have properties that are not automatically a consequence of being a member of the class. All humans have a heart, but not all humans have your name and date of birth.
I hope that clears it up a bit?
int main()
{
int a; //An instance of integer
int a,b; //two instances of integer
struct1 a; //An instance of struct1
return 0;
}
Here is a pretty standard definition:
An instance, in object-oriented programming (OOP), is a specific
realization of any object. An object may be varied in a number of
ways. Each realized variation of that object is an instance. The
creation of a realized instance is called instantiation.
Each time a program runs, it is an instance of that program. In
languages that create objects from classes, an object is an
instantiation of a class. That is, it is a member of a given class
that has specified values rather than variables. In a non-programming
context, you could think of "dog" as a class and your particular dog
as an instance of that class.
http://whatis.techtarget.com/definition/instance
Here is a good conversation about instances that may help you out: https://softwareengineering.stackexchange.com/questions/99202/is-it-called-class-or-object-instance
An object from an object or reference from an object.
Loosely speaking, there are patterns for making things and there are instances of those patterns.
A class is a pattern for creating objects. The objects that are created with it are instances of the class.
class C { };
C c; // instance of C
C d; // instance of C
A function template is a pattern for creating functions. The functions that are created with it are instances of the template. This is usually done implicitly, and referred to as "implicit instantiation".
template <class T> void f(T) { }
f(int); // implicit instantiation of f<int>
f(double); // implicit instantiation of f<double>
A class template is a pattern for creating classes. The classes that are created with it are instances of the template.
template <class T> class X { };
X<int> xi; // X<int> is instance of X, xi is instance of X<int>
X<double> xd; // X<double> is instance of X, xd is instance of X<double>
An instance is basically an object. In actual english, it can mean differently. In this case instance in english can mean 'To Refer' or 'Reference'. These objects instances in programming are also a reference to the source code.
with a simple example : we have a blueprint (class) represents student (object) with fields like name, age, course (class member). And we have 2 students here, Foo and Bob. So, Foo and Bob is 2 different instances of the class (Student class) that represent object (Student people).
credit: Alfred’s Computing Weblog
as far i have understood instance a pointer to object of class.
ps: i could be wrong.
Instance is a variable that holds the memory address of the Object.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Java/C# method representation in memory
I was wondering if i have an object in java, how are it's instance methods stored? Does an object have a pointer to it's instance methods?
Example:
public class MyObject {
private int x;
private int y;
[..]
}
If i plan keeping a lot (A big tree of objects for example) of these MyObjects in memory, will it make a significant difference in memory terms if apart from a getter for x and for y i define an instance method calculating the sum?
I'm trying to sort out wether i should add more instance methods or doing the calculations in another class using the getters and setters.
The instance methods of an object are stored in its class object (only one copy should exist), they are not "copied" with each new instance, instead, under the hood each instance holds a reference to the method implementation residing in the class object.
For a technical explanation, take a look at this chapter from the book "Inside the Java Virtual Machine", in particular the "Object Representation" section; it details how each instance of an object references its methods in the corresponding class. Notice that the implementation details for this are not present in the JVM specification, and they're left open to the implementors - the linked document presents several strategies.
The object needs memory for its attributes (NOTE: for object, the attribute stored is a pointer to the real object, which lies elsewhere in memory). No additional memory is needed for methods (code) as they are stored with the class.
IE:
public class MyClass1 {
private int myNumber;
}
and
public class MyClass2 {
private int myNumber;
public int MyMethod1() {
}
public int MyMethod2() {
}
public int MyMethod3() {
}
....
public int MyMethod1000() {
}
}
use the same memory per instance.
They are stored inside the class. Details are in the JVM specification.
No it will not make a significant difference. The method is actually stored in the class definition file MyObject.class. There is only one instance of that method. It gets executed for each instance but is only defined once.
Each instance is associated to a class.
The class defines the methods for all instances.
Because of this, there is no need to have pointers to methods for each instance.
An instance just store the values of the non static attributes
If you want to know the class of an instance, you just use instance.getClass().
By using getClass() you can access the list of all methods at runtime.
I'm confused with variable declarations in Java code.
I read... don't try to use global variables declarations .
Don't use something like this:
package cls;
public class test {
private String var;
public someMethod(){ ... }
}
And use ?
package cls;
public class test {
public someMethod(){
String var = null;
}
}
I don't know which is the correct way....
It totally depends on what you need.
Your first example, however, isn't a global variable--it's an instance variable.
Variables should have as small a scope as possible. This makes code easier to reason about.
Instance variables are central to what OOP is all about--classes (objects) exist to encapsulate object state, and the methods that operate on that state. For example, a Person class would likely have first and last name instance variables:
public class Person {
private String firstName;
private String lastName;
// Plus getters and setters for each.
}
This allows instance methods to access the first and last name variables directly without having to pass them between all the methods that need them.
The second example is a local variable. It's visible only in the method it's declared in. A reference to it may be passed to other methods.
Both are correct. Neither of those are global variables. The first one is a class field. It's unique to each instance of the class that you make. Class fields (ie. variable) stay with the instance of the class until the class itself is deleted.
The second one is a method scope variable. It's only there for temporary purposes to perform the calculations needed for the method to work, and once the code in the method is done, the variable goes away.
You use each for different purposes. For example, if you're writing a Car class, you'd probably have a class field for SteeringWheel and Brake. But if you had a method to calculate the average miles per gallon, you might create a method scoped variable to help perform the calculation.
Java doesn't have global variables. The first variable is class level and maintains the state of class instances and hence exists as long as an instance of the class while the second is a method's local variable that exists only during method's execution. You can use the first variable to store state information that spans multiple method calls. The second variable disappears as soon as the control leaves the method. Also, every time you call the method another variable, accessible by the same local name is created on the stack.
You can't have truly "global" variables in Java the same way as you can in a language such as C. Java forces you to structure your program in an object oriented way.
In your example above, if var is required throughout a whole test object and is important to have stored, then you would use the first example. If var is only required in someMethod and it's not important for a test object to store it then use the second example.
Take note that even with the first example, var is encapsulated within a test object, so it's not really "global" at all, apart from maybe slightly to the member function of test (which is the whole point of instance/member variables).
The closest thing in Java to "global" data is something like:
public class GlobalVars {
public static int globalInt;
}
And you could access globalInt throughout your code as GlobalVars.globalInt, without creating an instance of GlobalVars.
So I'm learning java. I'm one month in and I just learned about constructors. But I don't see the whole purpose of creating one. Why and when would I ever want to use one? I get the whole idea that it does not have a main method and you can call a constructor from your main class. Anyone can enlighten me on this topic, it would help me a great deal.
Constructors are what you use to initialize/set up the instances of your classes.
If you have an object that needs some processing before it is usable (initializing members for instance), you should do that in the constructor.
Ideally, you should never have "partially built" objects (i.e. objects that are "live", that you hold a reference to, but that are not yet usable). Without constructors, you'd be permanently creating partially built objects, and that is very error-prone. (Theory and practice don't always match, but keep that idea in mind.)
You use a constructor to create new objects. Yes, you can write Java just using static methods - but then you're really not writing object-oriented code, and you'll have a hard time using much of the standard library, either.
Most of your time you should be working with and thinking in terms of objects - and they need to be constructed before they can be used... and that's where constructors come in. They create an object, often with parameters specifying the initial state or other important information about the object.
To be honest, it's probably not worth worrying about them just yet, if you don't see the point yet. It's likely that as you learn more, you'll naturally start using objects more (maybe collections to start with, for example) and you'll get the hang of it. Rest assured, it is important to have constructors in Java, but I'm sure you'll understand why in the course of time. (Of course, if this answer has helped you to appreciate their value already, I'm glad - but if not, don't worry :)
It might seem as if you're having trouble understanding the basic concepts of objects and object-oriented programming. An explanation by example; This class represents a type of thing, namely a car:
public class Car{
// Licence plate number. This is private, so it can
// not be accessed directly from outside the class.
private String hiddenRegNr = "";
private static String description = "This is a car".
// The constructor, which sets the value of hiddenRegNr
public Car(String regNr){
hiddenRegNr = regNr;
}
// Method for reading hiddenRegNr, the only
// way to access it after instantiation.
public String getRegNr(){
return hiddenRegNr;
}
// A static method. Can be used withouth instantiation.
public static String getDesc(){
return description;
}
}
From some other class, you could call this class, and make instances of it; actual representations of different cars. They represent different cars, but are based on the same "model", i.e., the class Car.
Car myFirstCar = new Car("SR12345");
Car myOtherCar = new Car("XZ54321");
Now you have two different cars, with two different registration numbers. These are independent instances of the type car. They exist in memory, and may contain different values (in this case, different registration numbers).
myFirstCar.getRegNr(); // Will return SR12345
mySecondCar.getRegNr(); // will return xz54321
The first thing to notice here, is that you can only specify the registration number once per car, namely upon creation. That is the point of the constructor: It sets values, and does other stuff that needs to be done when objects (instances) are created.
Now, note the difference between getRegNr() and getDesc(): The keyword "Static" means that the second method is related directly to the class, and not to each instance. This means that:
Calls to getDesc() is made on the class, not an instance:
Car.getDesc();
Calls to getDesc() will return the same value for all instances of the class car
The variable description (which is also static) will be the same for all instances of Car
The static method getDesc() CAN NOT access the variable hiddenRegNr, since that variable is related to a specific instance. Trying to refer to a variable in an instance from a static context (such as getDesc()) will cause an exception to be thrown. You might say that hiddenRegNr will not have been set when you call
Car.getDesc();
because the constructor was never called, so it was never given any value.
Constructors are used to initialize a class and give parameters to a class. What is important is that they let you set the class state on creation. This allows you to use specific instances of a class with different data field values instead of relying on purely static information. Take the following example:
class Obj {
private int state = 0;
public Obj(int state) {
this.state = state;
}
public Obj() {
state = 1;
}
}
Now in main (or wherever) you can have:
Obj obj1 = new Obj();
Obj obj2 = new Obj(2);
The two objects have different states (one is at state 1, the other is at state 2). If you were relying on static methods and members, the objects would share one state and would not be independent of each other.
It is also important to note that constructors (specifically the new keyword) allocate memory for a given object internally so you don't have to worry about using malloc and other memory management. So they are important in that sense as well.
It is used to create objects. Objects are the main concept in OOP, so creating them is an important step. The main class method is just an entry point to your program. If you don't create objects your program will be procedural rather than object-oriented. This is why to use a constructor.
And why to create a constructor - sometimes you need to construct an object with some required parameters. There is also a default no-argument constructor, but if you want to initialize your object with additional arguments - you create a constructor taking those arguments.
Actually constructor is needed IF you need to assign unique initial state to an instance of a class. In Java i only just realized (by a friend) that we can do this:
public class MyClass1 {
private class MyClass2 {}
private MyClass2 myobj2 = new MyClass2();
}
So no need for implicit constructor.
But if something like follows, you need constructor.
public class MyClass1 {
private class MyClass2 {
private int id_ = 0;
public MyClass2(int id) { id_ = id; } // how to reach this?
}
private MyClass2 myobj2 = new MyClass2(1); // (this doesn't work. Not unique)
public MyClass1(int id) { myobj2 = new MyClass2(id); } // by this!
}
MyClass1 obj1 = new MyClass1(100);
MyClass1 obj2 = new MyClass1(200);
I will give you an example, imagine you have a car class.. when you call the constructor of the car class you have an car object. on this car object is possible to use diffent methods. And you could create as many as car objects as you want.