In multiple explanations, it is explained that only one object is created during inheritance. However, during inheritance from a superclass, a subclass does not inherit its parent's private attributes.
However, when a subclass calls its parents non-static getter method, it clearly is taking the value from some parent object, not a class. Then it seems that when you create a subclass object, a superclass object is also created that stores those private attributes.
Then are there essentially two copies of inherited methods and attributes? For example, if a superclass object A has a subclass object B. Then inside B there is both a super.attribute and a this.attribute because a hidden A object is also created?
How then do constructors know the difference between attributes? For example, A has a constructor that sets a public attribute to 4. B then calls that constructor and sets the same attribute to 5. But B inherits that attribute as well, no? So does it get reset to 4? Or does the super.attribute = 4 and this.attribute = 5? Thus an attributes' value isn't inherited, but its existence is?
Java always creates only one object when you create a new instance of any class, regardless of how many other classes it extends.
When the object is being instantiated, it contains all of the public and private fields but they are all available only in their specific scope.
If you need to know more about how the object is being stored in memory, here's an example:
class A {
private boolean attribute;
}
class B extends A {
private boolean attribute;
}
B inst = new B();
In this case, inst will be a single object which contains both private fields - one can be accessed only inside A, the other - only inside B. JVM does not store fields by their names - fields are just a section of memory and JVM handles them separately.
If you want to know more about the inner representation of your class, I highly suggest Java Object Layout tool (https://github.com/openjdk/jol) or related extension for IntelliJ Idea (https://github.com/stokito/IdeaJol). In case of this example, it shows that resulting class looks like this in memory:
Instance size 24 Losses total 10 Losses internal 3 Losses external 7
Offset Size Type Class Field
0 12 (object header)
12 1 boolean A attribute < private field of A
13 3 (alignment/padding)
16 1 boolean B attribute < private field of B
17 7 (loss due to the next object)
Related
This question already has an answer here:
What happens in the heap when class A inherits class B in Java
(1 answer)
Closed 3 years ago.
Consider a Superclass A and a derived class B whereas A contains a private variable x. B contains an explicit super() call as first argument inside its constructor while there might be some other variables of B like y and z. As far as I know there is no inheritance for private fields. Does that mean private fields will not get instantiated while executing:
B b = new b();
My question is: How does the heap look like after running the above code? Of course there will be y and z, but what about x in this case?
Field inheritance and field visibility are two separate concepts, not to be confused.
Field inheritance
In a way (to simplify a bit), a class is a template from making objects. So if a class A declares two fields f1 and f2, then instantiating A creates objects (and allocates memory for them on the heap) that have these two fields.
A subclass is also a template for making objects, but this template is expressed as an addition to another class. So if class B declares field f3 and extends A, it's basically saying, "take all the fields that A defines, and add f3". So instantiating B results in an object with three fields f1, f2, f3.
Field Visibility
Field visibility, as expressed through access modifiers like private and public, is a way to control which part of the code "sees" (or can refer to) a certain field. The private modifier means that no code outside of the class that declares the field can refer to this field. However, it doesn't mean that the field stops existing. To make a dodgy parallel, if you and another person are in a room and you turn off the light, you can't see the other person, but they are still there.
To emphasize the point that the concepts are separate, consider that in some cases you can see fields that are not inherited (e.g., because they are non-private, but in a class not in the same class hierarchy). And in some cases you can't see fields that are inherited, as in the case of private fields in the superclass.
The private field defined in the super class is instantiated when a statement does that.
The fact that you manipulate a subclass doesn't change anything on this point. The field is always existing and instantiable, just the subclass cannot access it directly.
If the field of the super class was not instantiable, the Java inheritance would make not any sense since the subclasses would be not consistent or even unusable as superclass methods will not work any longer.
For example :
private int x;
A(){
this.x = getIntValue();
}
int getX(){return x;}
And B the subclass :
B(int x){
super(); // in the compiled code even if not in the source code
}
new B().getX() will of course return the value of x instantiated in the superclass.
I am confused as to the purpose of empty constructors, let me ellaborate:
if I have a class..
public class Test {
private int x;
private int a[];
private static int y;
public Test() {
a = new int[3];
}
}
I know that there exists an empty default constructor:
public Test() {
//or at least I think it exists
} //what is its purpose?
if I have a main method and code the following:
Test t1 = new Test();
Which constructor is called? or is the empty constructor overwritten by the one which instantiates a[]?
If I then instantiate 5 instances of Test, how many integer memory locations are allocated?
Sooo confused....
The empty constructor is inherited from the Object class, which is the superclass of all classes in Java. It merely allocates memory of the objects, but does not initialize anything.
So for every object it is possible to call new A(), even if public A() is not defined explicitly.
Sometimes you don't need to do extra job in the constructor, so you can just use the default one without bothering reimplementing it.
When a child class overwrites it, then the one called is the new one. It makes perfect sense, because when you bother overwriting a method, you want to be able to use it instead of the default one.
In your examples, the Test class contains 2 integers, and an array of 3 integers.
Each time you instantiate a new Test, you allocate space for two more integers and the array of three integers. This is why those are called instance variables: it means they belong to an instance. So each instance has its own.
If you do not define any constructor for your class then compiler will automatically add a default parameter-less constructor to your class definition so that objects can be created using new keyword. If you explicitly define a parameter-less constructor (the way you have done) yourself then compiler will not add anything from his side.
So in this line of code
Test t1 = new Test();
the constructor that you have defined explicitly will be called.
To answer your second question - Each instantiation of your class results in allocation of memory required to hold an array containing 3 integers. For 5 instances it will simply become 5 times.
i.e. 5 * 3 * memory occupied by one integer
Which constructor is called? or is the empty constructor overwritten by the one which instantiates a[]?
Since you have provided constructor for Test class, your constructor will be called. If you want to call super class constructor explicitly, change your code as
public Test() {
super();
a = new int[3];
}
From oracle documentation page on constructors
You don't have to provide any constructors for your class, but you must be careful when doing this. The compiler automatically provides a no-argument, default constructor for any class without constructors. This default constructor will call the no-argument constructor of the superclass. In this situation, the compiler will complain if the superclass doesn't have a no-argument constructor so you must verify that it does. If your class has no explicit superclass, then it has an implicit superclass of Object, which does have a no-argument constructor
If I then instantiate 5 instances of Test, how many integer memory locations are allocated?
JVM will allocate space for 1 integer for static variable ( int y, which is class or static variable)
JVM will allocate space for 1 integer for each Test instance for int x, which is instance variable
JVM will allocate space for 3 integers for each Test instance for int a[] array, which is instance variable
Total : Space for 5 + 5 + 15 (=25) integers
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.
I am trying to understand how inheritance is realized inside JVM. It seems to me, that if we have the following code:
class A {
int aa;
}
class B extends A{
int bb;
}
....
B b=new B();
Inside the JVM three objects will be created:
object of B (with field int bb),
object of A (with field int aa)
object of Object.
Of course the programmers see only one object of class B. Am I right? Or is only one object created inside JVM?
What I think:
The new returns the reference to B. Why I think so is (for example) that if we override some method from A in B we can always get it using super. Besides in default constructor B the first line will be call to default constructor A in which we can call the constructor on certain object ONLY IF this object exists. Therefore a separate A object exists?
At first, the spec says that the internal structure of objects is not specified, so in theory, a JVM could internally create more than one object, where B contains only fields new to B, and a link to an A object, which contains the fields of A.
It also says something about the Oracle JVM implementation: A class instance contains three pointers. One to a method table, one to some space in heap where the data of the instances fields is, and one the Class object that instance belongs to.
You can conclude from that, that there is only one instance per object created, namely the instance of B. The method table for this instance contains all methods from B, A and Object, as well as the heap space contains all data from fields from B, A (and Object).
Here only one object will create. it is B object. But B object has state and behaviors of A object. As super type of every class is Object class, B object has Object's state and behavior too. Thanks
Classes represent a type of objects, but only instances create real objects. So only one object is created and it corresponds the result merge of class B with class A.
In a nutshell, how and why is this possible:
Object obj=new MyClass();
Object is the superclass of all objects, therefore MyClass is a child class of Object. In general, in Java, Why is it possible to use the constructor of a child class in the parent class?
I understand how it could go the other way around, since the child has all the variables/methods of the parent class, so when you initialize them you are just initializing the variables specified in the parent constructor, that exist by definition in the child. The problem is, when you go the other way around, it is not necessarily true. A child can have variables the parent doesn't, so how is it possible to use the child constructor with the parent, when the parent does not even have the variables in the first place?
What uses does this feature have in development? I would think that if you want an instance of class B, you would declare it as B thing=new B(), and not A thing=new B(). This is probably my inexperience talking, so I would appreciate enlightenment on why and how a parent class can be initialized as one of its children.
Why is it possible to use the constructor of a child class in the
parent class?
This is not correct. When you do
Object obj = new MyClass();
Object obj; declares a reference of the type Object
and new MyClass(); returns a reference to the object it created.
So, you are instantiating a MyClass and assigning the reference to the object created to a reference of the type Object, and this is possible because MyClass is an Object.
As you say,
A child can have variables the parent doesn't
That's called extending the parent functionality (inheritance).
For your second question think about the classic Animal example: Suppose you create a Animal class and you create a method makeSound() on it.
Now you create two subclasses of Animal, Dog and Cat, that overrides the makeSound()method of Animal (a Dog barks and a Cat meows).
Imagine that you represent a room full of Animals (Dogs and Cats) using a List, and you want to make all of them makeSound(). Your list will be declared as List<Animal> because you don't know the kind of Animals that you will store.
And then you iterate over the List to call makeSound() for each Animal. It doesn't matter if the Animal is a Dogor a Cat, it will make it's sound.
And then imagine you want to add Birds to the List. Easy, isn't it?
You are thinking in terms of C++ semantics, but this is Java. In Java, all non-primitive type variables are references, not instances.
In C++, when you say
Object obj;
you allocate a new Object instance on stack or in static memory.
When you say
Object obj = new MyObject;
you invoke a constructor of Object class that takes MyObject pointer (or may be something else that MyObject can be converted to).
In Java,
Object obj;
does not create any instances of Object. It simply creates a variable that can have a reference to an Object instance, but at the moment does not refer to any. It is initialized to null.
Object obj = new MyObject();
allocates an instance of MyObject. It does not allocate a new instance of Object. It simply sets the variable to refer to the new instance. In C++ terms this is much more similar to
Object *obj = new MyObject();
So we're not constructing a parent instance from child instance. We're changing a value the variable is set to, from null to a new child instance.
First, you must get a clear understanding of things. Your example expression:
Object obj = new MyClass(); is actually a compound of two elementary operations.
The first one is creating an instance of MyClass: new MyClass(). The new keyword is basically the only way of actually obtaining an instance of a class (lets ignore runtime reflection to keep this simple), and you are literally naming what you want to create (MyClass) here by its constructor. There is no way to create anything other than what you literally named with the new keyword. The result of new is (implicitly) an instance of MyClass, but the explicit result of a new X is a reference of type X (the reference referring to the newly created instance).
Now the second operation is assigning the reference to your (new) MyObject to another reference of type Object. And this is valid because MyObject is an Object (due to inheritance).
Why would you need this?
This is an essential feature to actually make use of polymorphism. The ability to refer to any child class as its superclass is what makes polymorphism so powerful. You basically will use it everywhere where there is an aspect common to two classes, but there are also differences.
A real world example would be graphical user interfaces. There are buttons, lists, tables and panels in a window, which are all user interface elements, but each does a different thing. To present them neatly organized in a window, these elements are often nested into panels, more abstractly said into containers. Now a container doesn't care what kind of elements go into it, as long as they are components. But to handle them properly a container does need some basic information about these components, mostly how much space they occupy and how to actually draw them. So this is modelled as something like:
public abstract class Component {
public int getWidth() { ... }
public int getHeight() { ... }
public void paint(Graphics g) { ... }
}
public class Container extends Component {
public void add(Component child) { ... }
public void paint(Graphics g) {
for (Component child : children) {
child.paint(g);
}
}
}
Thats almost straight lifted out of the JDK, the point is, if you needed to refer to each Component as its concrete type, it would be impractical to build a Container, it would need extra code for each Component you decide to make (e.g. there would be an addButton, addTable and so on). So instead, Container just works with reference to Component. No matter what Component is created (e.g. Button, CheckBox, RadioButton etc.), since Container just relies on them to all be Component's, it can handle them.
Every class in Java is descended from Object. So MyClass is an Object, by definition, but a more specialized version of it. Think of it like this: every living creature is an Animal. A Cat is a special kind of animal; a specific type. Since the Cat is an Animal, you can still just call it an Animal:
Animal a = new Cat();
But doing so, with a, you can't do anything specific to a Cat, like meow() or purr(), but you can call methods which are valid for all Animals, such as breathe().
HTH
class myMobile{
public void call{
System.out.println("Mobile");
}
}
public class mainClass{
public static void main(){
Object o=new myMobile();
//here we can call methods which are common to all
// objects not specific to
// myMobile object
}
}
Because a MyClass is a Object. Note that java is special because Object is the superclass of every other class type (there is no equivalent in C++).
A more interesting example would be if you had a class or interface and one or more subclasses. This comes up all the time in OOD. Consider for example java's jdbc API: a common set of interfaces to connect and query a database that can be implemented by different concrete classes. You only need to code to the API and then at runtime use the implementation for your DB of choice.
http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html
Class Object is the root of the class hierarchy. Every class has Object as a superclass. All objects, including arrays, implement the methods of this class.
i.e. every Java class is an Object. This is why.
http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html
The Object class, defined in the java.lang package, defines and implements behavior common to all classes—including the ones that you write. In the Java platform, many classes derive directly from Object, other classes derive from some of those classes, and so on, forming a hierarchy of classes.
You have two separate things here:
The construction of a new instance
The assignment of that instance to
a variable
Since your instance of MyClass is also an instance of Object, this works well.
Consider the following, generic situation:
class A extends B implements C,D {
}
As your A is a B and also a C and a D and an Object, once you created an instance, you can (directly or indirectly) assign it to variables of all those types:
A a = new A();
B b = a;
C c = a;
D d = a;
Object o = a;
Your view on the fields or methods is limited by the type of the variable (i.E. as variable of type C, you only see the methods declared by C).
Nevertheless, your instance is always of the type you instanciated using the constructor, regardless of the variable type.