Where is information about methods of Java objects kept? [duplicate] - java

This question already has answers here:
What's the method representation in memory?
(3 answers)
Closed 9 years ago.
My colleague just asked me a really interesting question and I cannot give him an answer.
Let's assume that we have got the following class:
public class Person {
String name;
public Person(String name) {
this.name = name;
}
public void print() {
System.out.println("xxx");
}
}
Now, we are creating the objects:
Person p1 = new Person("a");
Person p2 = new Person("b");
Person p3 = new Person("c");
Person p4 = new Person("d");
Person p5 = new Person("e");
Person p6 = new Person("f");
Person p7 = new Person("g");
Person p8 = new Person("h");
The question was:
Do we keep information about the available methods in each single object? If we create a new object p9, will the JVM create the object with information about only fields or will it also add to this object information about methods?
Another question:
What happens if I invoke p1.print()? Does p1 have to ask the Person class to provide this method, or is it already saved in p1 object?

The code for methods isn't duplicated for all the instances, that would be completely unnecessary. The code lives in a special area in the memory, and it's shared by all the instances. The memory required by instance variables on the other hand naturally is owned by every instance.
As to how a method is called, the object doesn't really need to ask the class every time it calls a method, it has a pointer to the method's code and can just call it right away.
For more information on the inner workings of the JVM, refer here: http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-2.html

In general, code is represented once, no matter how many objects there are. The OO concept of objects "having" methods is just an abstraction. So, in essence, regardless of whether you method is instanced or static, behind the scenes it still "belongs" to the class.
For final methods, the call uses static binding (it's already predetermined which method will be called, based on the type of the expression).
For virtual methods, something more interesting happens. Depending on the implementation, either the object contains the address to the correct method (not the method itself, again) or the runtime reflects on that object to determine its actual class and find the appropriate method in the hierarchy.

I don't know how the Oracle JVM does it, but in general object-oriented programming systems, an object has a hidden instance variable that points to its class. All of the instances point to the same class object, and the pointers to the instance methods are part of the class.

JVM does a wonderful job by not binding object and methods together. To understand it's functionality clearly you need to understand it's underlaying architecture.
JVM has a class loader system which consist of below resources:
Method area
Heap
Java Stack
PC register
Native method stack.
When we create an object the class gets loaded(lazy load) and it gets all the required resources. Here in method area all the methods reside and objects reside in heap and which are shared among all the threads. JVM allocates/organizes all the memory needed to execute a program into several runtime memory areas.

Related

How does class object relation work?

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

Some classes need initialization and some don't

I already tried to search for an answer on the "using the new keyword" but didn't found an answer on my specific question.
Why do some classes have to be created with the keyword new and some don't
For example :
import java.io.BufferedReader
If you want to use this you have to create a new instance
BufferedReader read = new BufferedReader (..............)
But for example with system.console which also needs an import java.io.console. when you want to use this you can just type Console c = system.console()
i'm a beginner in Java and OO programming and found a couple of this examples troughout my book.
Thx for the help
In java, fields(aka Attributes) are always associated to either instance or to class.
There could be many instances of a class and to create instance you have to use new operator. To access instance related attributes, you will need to create one and this will be accessed as
ClassName instanceName = new ClassName();
instanceName.methorOrAttributeNameGoesHere
For class associated attribute aka Static attribute can be direcly accessed as ClassName.methorOrAttributeNameGoesHere
These are very basics of Java and probably you should first read some good book on Java and OOP like 'Head First Java'
The simple answer to this is that instantiation like new BufferedReader() always creates a different instance each time you call it; invoking a method like System.console() might or might not give you different instance.
Ultimately, all objects are instantiated via new; you just might not see it in your code.
Here are a couple of ways in which System.console() might be implemented (totally simplified, not actually like it is):
// (1) Returns new instance each time
class System {
static Console console() {
return new Console();
}
}
or
// (2) Returns same instance each time
class System {
private static final Console CONSOLE = new Console();
static Console console() {
return CONSOLE;
}
}
(There are infinitely more ways to implement it, these are just two examples. You can see the way it is implemented in OpenJDK by looking at the source code - it is similar to (2), in that the same instance is returned each time, just with a few more complications that I don't want to describe here)
In (1), if you invoke System.console() twice, you will get back two different instances of Console:
System.console() != System.console()
In (2), if you invoke System.console() twice, you will get back the same instance of Console:
System.console() == System.console()
The question I would ask here is do I need to care if I get back different instances or the same instance? The answer is probably not, if the API designer has done a reasonable job.
The decision as to whether expose the creation of a new Console was made by the person who wrote the classes. There are a number of reasons why he/she might not want you to create a different instance each time you invoke that method, e.g.:
The thing you are creating might be very expensive (slow, takes up lots of resources etc), so you don't want to create lots of them;
The thing you want has logically just one instance (it is a singleton).
There are a number of reasons why he/she might want you to create a separate instance each time you invoke that method, e.g.:
You don't want all of the places using that instance to share state. You have to worry about things like thread safety when instances of mutable classes are shared.
And there are a number of reasons why you might not want the user to invoke the constructor directly:
new Console() creates an instance of Console exactly; things like consoles are often platform-dependent, so you might actually want an instance of WindowsConsole, MacConsole etc to be returned when run on Windows, MacOS etc. If WindowsConsole and MacConsole extend Console, either of these can be returned from the System.console() method.
Prior to the introduction of the diamond operator <> in Java 7, it was necessary to include the full generic parameters in the new statement, e.g. ArrayList<HashMap<String, List<String>>> list = new ArrayList<HashMap<String, List<String>>>();; however, generic methods allowed this to be written as ArrayList<HashMap<String, List<String>>> list = newList():
<T> List<T> newList() { return new ArrayList<T>(); }
(Sometimes, you need a lot of parameters to pass to the constructor, and it is convenient to use the Builder Pattern. This isn't relevant to the cases in the question, but it is a reason for not invoking the constructor directly.)
The thing is that these are internal implementation details, and should be encapsulated: you, as a user of the Console class, shouldn't need to care about how expensive it is to create, or whether there is shared state: you just want a Console.
This encapsulation is effected by providing a method like System.console(): you don't need to know whether the method is implemented like (1) or (2) above (or any other method).
Additionally, if the class is originally written like (1), and that proves to be problematic, its implementation can be changed to (2) without you, as a user of the System class, needing to update your code.
This might be a bit too much detail for a beginner, and I can try to help you understand more; the long and short of it is that sometimes it is be better if you don't create instances directly.
System.console,console is static thats why we are calling it with class name directly,and to call the non static method we generally used the objectname.methodname .
The java.io.Console class is attached with system console internally.System class provides a static method console() that returns the unique instance of Console class.Thats why we used to do as Console c = system.console();
Please read about Static classes and non static classes method invocation/instance creation for more details.
Static methods don't require an instance, but non-static methods do. System.console() is static, butnew BufferedReader(...).read(...) is not
Static methods are typically used when the outcome of the method will never change based on the context. For instance:
Math.abs(-3); //will always be 3, no matter what
However consider this class:
public class Person {
private String name;
public Person(String name){
this.name = name;
}
public String getName() {
return name;
}
/*
* In this world, no special characters are allowed in a person's name
*/
public static boolean isValidName(String name) {
if (name.contains("!#$%&(=?") {
return false;
}
return true;
}
}
Person mySister = new Person("Mary");
Person myBrother = new Person("David");
Calling Person.getName() doesn't make any sense; this is like asking "What is a person's name?" without specifying who the person is. Now if you ask me "What is your sister's name?", then I can call mySister.getName() and give you a sensible answer.
Re: your comment "how do you know when to not use new"
If you are trying to create a new Person object (imagine you just had a baby), but you are wondering whether or not that amazing name you found on the internet will be accepted by the authorities:
boolean validName1 = Person.isValidName("LordVoldeMort!!!!!"); //returns false
boolean validName2 = Person.isValidName("HarryPotter2016"); //returns true
Person myLittleBabySon = new Person("HarryPotter2016"); //Accepted by authorities

Objects Within Objects in Java

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.

How are instance methods stored [duplicate]

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.

what's the point of java constructor?

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.

Categories