Compile and run-time classes - java

Lets imagine I have a class called Person which is a generalization of another class Man. If I am to make a couple of instances of this class
Man man = new Man();
Person person = new Man();
Now, the compile-time class of the instance being referenced from the variable man is Man and the compile-time class of person is Person while the run-time class of both instances is Man. So far, im completely on board with the terminology because the instances which are created at run-time both are of class Man. But, if I where to cast the man instance as follows
Person personMan = (Person) man;
how come the run-time type of personMan is still Man? Is the run-time class of a instance only set when a new instance is created? Also, is there a way of actually getting the compile time class of a variable at runtime, so I could query what type of class personMan is (getClass would return Man).
Edit: "compile-time class of a class" was a mistake (and doesn't make much sense). What I meant was variable (hence they question about what type of class personMan is :))

It's important to distinguish between three different concepts here:
Variables (man, person)
References (the values of the variables)
Objects (the blobs of memory that the references, um, refer to)
The type of an object never changes after it's created. Casting a reference to a different type only affects the compile-time type of that expression. The result of a reference-type cast expression is always the same the original reference - it still refers to the same object, which still has the same type. (That's leaving boxing aside - and of course the cast can fail at execution time, leading to an exception.)
Also, is there a way of actually getting the compile time class of a class at runtime
If you mean the compile-time type of a variable - not if it's a local variable, without really deep inspection of the byte code. If it's a field you can use reflection to get at it. Why do you want to know?

The runtime type is the type of the new. new Man() is always Man, no matter the type of the variable where you store it.
The compile type is the type of the declared variable.
In your example
Person personMan = (Person) man;
you only can code with methods and attributes of personMan. You can also do
((Man)personMan).someManMethod();
but this can lead to a error if personMap hasnĀ“t stored a instance of Man.

In Java, variables (other than primitives) are just references to objects. The objects themselves live off somewhere else and can never be directly accessed.
In every case, you have a Man object sitting somewhere, and the different references just give access to different subsets of the capabilities of that Man object.

Related

Using instanceof to seperate classes in an ArrayList

apologies if this is simple or has been answered before, I'm new to Java and in my research I can't find too much on this issue and have not yet found a solution.
I have an ArrayList with multiple classes that all share a common Interface, in this example the interface is called "Packable". I'm trying to create a method that takes a class parameter and sweeps through each element of this ArrayList, returning a new list containing all the items in the original list that are of the same class as the reference parameter.
This is my code so far, trying the instanceof method:
public List<Packable> getOfType(Packable reference){
List<Packable> typeOfItems = new ArrayList<>();
for (Packable item: itemsStored) {
if (item instanceof reference){
typeOfItems.add(item);
}
}
return typeOfItems;
}
This is throwing an error as it doesn't yet recognise reference as a class. This question mentions a method isAssignableFrom with the answer stating: "When using instanceof, you need to know the class of B at compile time. When using isAssignableFrom() it can be dynamic and change during runtime." (Thanks Marc Novakowski)
I understand that given the parameter the class isn't known at compilation and as such I've tried implementing isAssignableFrom and can't really seem to get it to work. The IDE doesn't really recognise or suggest it, and there isn't too much about the method online. I've tried implementing it the way the JavaDocs suggest but this isn't working either:
if (reference.isAssignableFrom(item.getClass())){
typeOfItems.add(item);
}
Any help or advice on methods to look into would be greatly appreciated. Thanks for reading the question, and again apologies if this is simple or has been answered elsewhere and I've just missed it. Thanks everyone
I'm not sure what Packable is, but you appear to be confused about a few concepts here.
In java, Packable reference does not represent the Packable concept. It represents a specific instance of Packable (or null).
In other words, given Dog dog, that means dog is some specific dog. Not 'the general concept of a dog'. We know that the specific animal that dog is referring to is, at least, a Dog. It could be Fifi, the neighbour's schnauzer.
instanceof, on the other hand, is about the general concept of things: if (fifi instanceof Dog) is how you're supposed to use it. You're more or less attempting to do the equivalent of if (fifi instanceof rover) which just doesn't make sense. How can one dog be 'an instance' of another? It's not that the answer is 'true' or 'false', but that the very question doesn't even make sense, which is why javac doesn't compile it. It has no idea what this even means.
Java, being java, makes objects of many things. Notably including the very notion of things. Thus, there is the class java.lang.Class, instances of which represent classes. A bit of alice-going-down-the-rabbit-hole thing is happening here: Classes as a concept are also represented as instances of the java.lang.Class class.
A class OBJECT (so, an instance of java.lang.Class) has the .isAssignableFrom method. This in fact takes another j.l.CLass as argument, it's for checking if one type is a subtype of another. In that sense, the question linked is needlessly confusing - you're really looking for the instanceOf method (there is an instanceof language construct, but the j.l.Class class has an isInstance method, which is unrelated, other than that they roughly accomplish the same goal: Check if some INSTANCE is of a type that is equal to, or a subtype of, some TYPE.
This is an example of how to use it:
Class<?> c = Number.class;
Object o = Integer.valueOf(5);
System.out.println(c.isInstance(o));
this is more or less equivalent to:
Object o = Integer.valueOf(5);
System.out.println(o instanceof Number);
Except now the Number part no longer needs to be written at 'write the code' time, you can supply it, say, read it from a parameter. You'd have to, of course, dynamically construct the Class instance. You can do so either by string-lookup, or by getting the actual type of an actual object. For example:
String input = scanner.next(); // user types in "java.lang.Number"
Class<?> c = Class.forName(input);
Object o = Integer.valueOf(5);
System.out.println(c.isInstance(o));
Or:
Object i = Integer.valueOf(5);
Object d = Double.valueOf(10);
Class<?> c = i.getClass(); // will be java.lang.Integer.class
System.out.println(c.isInstance(d)); // false
But doing this latter bit is really dangerous. Often i.getClass() returns some hidden impl detail subtype (java is hierarchical and object oriented, anywhere, say, an ArrayList is needed, someone is free to make a new class: class MyVariantOfArrayList extends ArrayList, and use that - now you write ArrayList foo = getList(), but foo.getClass() doesn't return ArrayList - no, you invoke that method on the object the foo variable points at, so, it'd be MyVariantOfArrayList.class, not ArrayList.class.
It's possible Packable itself represents a type. But then it either needs to also have isInstance and isAssignableFrom and such (and you need to start questioning why you're badly reinventing the wheel here - java.lang.Class already exists!), or it needs a .getRepresentedClass() method. You can't call it .getClass(), as the JVM has already given all objects that method, and it would return Packable.class itself.

How do i understand, what is an instance of a class in Java [duplicate]

What is the difference between an object, instance, and reference? They say that they have to create an instance to their application? What does that mean?
An object and an instance are the same thing.
Personally I prefer to use the word "instance" when referring to a specific object of a specific type, for example "an instance of type Foo". But when talking about objects in general I would say "objects" rather than "instances".
A reference either refers to a specific object or else it can be a null reference.
They say that they have to create an instance to their application. What does it mean?
They probably mean you have to write something like this:
Foo foo = new Foo();
If you are unsure what type you should instantiate you should contact the developers of the application and ask for a more complete example.
"instance to an application" means nothing.
"object" and "instance" are the same thing. There is a "class" that defines structure, and instances of that class (obtained with new ClassName()). For example there is the class Car, and there are instance with different properties like mileage, max speed, horse-power, brand, etc.
Reference is, in the Java context, a variable* - it is something pointing to an object/instance. For example, String s = null; - s is a reference, that currently references no instance, but can reference an instance of the String class.
*Jon Skeet made a note about the difference between a variable and a reference. See his comment. It is an important distinction about how Java works when you invoke a method - pass-by-value.
The value of s is a reference. It's very important to distinguish between variables and values, and objects and references.
When you use the keyword new for example JFrame j = new JFrame(); you are creating an instance of the class JFrame.
The new operator instantiates a
class by allocating memory for a new
object and returning a reference to
that memory.
Note: The phrase "instantiating a class" means the same thing as
"creating an object." When you create
an object, you are creating an
"instance" of a class, therefore
"instantiating" a class.
Take a look here
Creating Objects
The types of the Java programming
language are divided into two
categories: primitive types and
reference types.
The reference types
are class types, interface types, and
array types.
There is also a special
null type.
An object is a
dynamically created instance of a
class type or a dynamically created
array.
The values of a reference
type are references to objects.
Refer Types, Values, and Variables for more information
I think that Object = Instance. Reference is a "link" to an Object.
Car c = new Car();
variable c stores a reference to an object of type Car.
Computer c= new Computer()
Here an object is created from the Computer class. A reference named c allows the programmer to access the object.
The main differnece is when you say ClassName obj = null; you are just creating an object for that class. It's not an instance of that class.
This statement will just allot memory for the static meber variables, not for the normal member variables.
But when you say ClassName obj = new ClassName(); you are creating an instance of the class. This staement will allot memory all member variables.
basically object and instance are the two words used interchangeably.
A class is template for an object and an object is an instance of a class.
"creating an instance of a class" how about, "you are taking a class and making a new variable of that class that WILL change depending on an input that changes"
Class in the library called Nacho
variable Libre to hold the "instance" that will change
Nacho Libre = new Nacho(Variable, Scanner Input, or whatever goes here, This is the place that accepts the changes then puts the value in "Libre" on the left side of the equals sign (you know "Nacho Libre = new Nacho(Scanner.in)" "Nacho Libre" is on the left of the = (that's not tech talk, that's my way of explaining it)
I think that is better than saying "instance of type" or "instance of class". Really the point is it just needs to be detailed out more.... "instance of type or class" is not good enough for the beginner..... wow, its like a tongue twister and your brain cannot focus on tongue twisters very well.... that "instance" word is very annoying and the mere sound of it drives me nuts.... it begs for more detail.....it begs to be broken down better. I had to google what "instance" meant just to get my bearings straight..... try saying "instance of class" to your grandma.... yikes!
The Literal meaning of instance is "an example or single occurrence of something." which is very closer to the Instance in Java terminology.
Java follows dynamic loading, which is not like C language where the all code is copied into the RAM at runtime. Lets capture this with an example.
class A
{
int x=0;
public static void main(String [] args)
{
int y=0;
y=y+1;
x=x+1;
}
}
Let us compile and run this code.
step 1: javac A.class (.class file is generated which is byte code)
step 2: java A (.class file is converted into executable code)
During the step 2,The main method and the static elements are loaded into the RAM for execution. In the above scenario, No issue until the line y=y+1. But whenever x=x+1 is executed, the run time error will be thrown as the JVM does not know what the x is which is declared outside the main method(non-static).
So If by some means the content of .class file is available in the memory for CPU to execute, there is no more issue.
This is done through creating the Object and the keyword NEW does this Job.
"The concept of reserving memory in the RAM for the contents of hard disk (here .class file) at runtime is called Instance "
Objects, which are also called instances, are self-contained elements of a program with related features and data. For the most part, you use the class merely to create instances and then work with those instances.
-Definition taken from the book "Sams Teach Yourself Java in 21 days".
Say you have 2 Classes, public class MainClass and public class Class_2 and you want to make an instance of Class_2 in MainClass.
This is a very simple and basic way to do it:
public MainClass() /*******this is the constructor of MainClass*******/
{
Class_2 nameyouwant = new Class_2();
}
I hope this helps!
Instance variable: It must be attached to the object. Instance variables in this class can only be used after instantiating the class
public class Test{
static int a = 13;
int b = 14;
public static void main(String[] args){
int d = new Test().b;
System.out.println(d);
}
}
Instance = memory is allocated at run time for anything that is called instance
Object = memory is allocated at run time for class that is called object

In java , can we pass superclass Object to subclass reference?

In java, can we pass superclass Object to subclass reference ?
I know that it is a weird question/practically not viable,
but I want to understand the logic behind this
Why is it not allowed in java.
class Employee {
public void met1(){
System.out.println("met1");
}
}
class SalesPerson extends Employee
{
#Override
public void met1(){
System.out.println("new met1");
}
public void met2(){
System.out.println("met2");
}
}
public class ReferenceTest {
public static void main(String[] args) {
SalesPerson sales = new Employee(); // line 1
sales.met1(); // line 2
sales.met2(); // line 3
}
}
What would have happened if Java allowed compilation of line 1?
Where would the problem arise?
Any inputs/link are welcomes.
If your SalesPerson sales = new Employee(); statement was allowed to compile, this would have broken the principles of Polymorphism, which is one of the features that the language has.
Also, you should get familiar with that does compile time type and runtime type mean:
The compile-time type of a variable is the type it is declared as, while the runtime type is the type of the actual object the variable points to. For example:
Employee sales = new SalesPerson();
The compile-time type of sales is Employee, and the runtime type will be SalesPerson.
The compile-time type defines which methods can be called, while the runtime type defines what happens during the actual call.
Let's suppose for a moment that this statement was valid:
SalesPerson sales = new Employee();
As I said, the compile-time type defines which methods can be called, so met2() would have been eligible for calling. Meanwhile, the Employee class doesn't have a met2() and so the actual call would have been impossible.
No. It makes zero sense to allow that.
The reason is because subclasses generally define additional behavior. If you could assign a superclass object to a subclass reference, you would run into problems at runtime when you try to access class members that don't actually exist.
For example, if this were allowed:
String s = new Object();
You would run into some pretty bad problems. What happens if you try to call a String method? Would the runtime crash? Or perhaps a no-op would be performed? Should this even compile?
If the runtime were to crash, you could use runtime checks to make sure the objects you receive will actually contain the methods you want. But then you're basically implementing guarantees that the Java type system already provides at compile-time. So really that "feature" cost you nothing but a bunch of type-checking code that you shouldn't have had to write in the first place.
If no-ops were executed instead of nonexistent methods, it would be extremely difficult to ensure that your programs would run as written when the members you want to access don't exist, as any reference could really be an Object at any point. This might be easy to handle when you are working on your own and control all your code, but when you have to deal with other code those guarantees essentially vanish.
If you want the compiler to do the checking, assuming compiler writers don't hunt you down and give you a stern talking-to -- well, you're back to "normal" behavior once more. So again, it's just a lot of work for zero benefit.
Long story short: No, it's not allowed, because it makes zero sense to do so, and if a language designer tried to allow that they would be locked up before they could do any more harm.
If you inherit from a class, you always specialize the common behavior of the super class.
In your example, the SalesPerson is a special Employee. It inherits all behavior from the super class and can override behavior to make it different or add new behavior.
If you, as it is allowed, initialize a variable of the super type with an instance of the sub type like Employee e = new SalesPerson(), then you can use all common behavior on that variable.
If instead, you were possible to do the other way round, there might be several uninitialized members in the class.
You find this very often when using the Java Collection API, where for example you can use the common List class on operations like iterating through it, but when initializing it, you use for example the sub class ArrayList.

logical structure/details of a reference variable and object in the memory?

Let's say we have a class:
class Class1
{
int i = 1;
}
and we have a variable:
Class1 ob1 = new Class1();
Does a reference itself stored in a variable ob1 store the information that it refers to an object of Class1?
Does the part of the heap where Class1 is stored store the information that it is of Class1 type?
How does logically looks like this information? It's a string like application1.Class1 or a reference to some reference types pool?
If you can recommend the source of such information I'll be very grateful for providing it I can't find it in the reference book.
Does a reference itself stored in a variable ob1 store the information
that it refers to an object of Class1?
NO. Reference variable ob1 stores only the reference of the object it points to. And the information about that object is already known to the application (or JVM).
Does the part of the heap where Class1 is stored store the information
that it is of Class1 type?
NO. The information about class being loaded is stored in method area. As specified in this link
For each type it loads, a Java virtual machine must store the following kinds of information in the method area:
The fully qualified name of the type
The fully qualified name of the type's direct superclass (unless the type is an interface or class java.lang.Object, neither of which have a superclass)
Whether or not the type is a class or an interface
The type's modifiers ( some subset of` public, abstract, final)
An ordered list of the fully qualified names of any direct superinterfaces
How does logically looks like this information? It's a string like
application1.Class1 or a reference to some reference types pool?
Inside the Java class file and Java virtual machine, type names are always stored as fully qualified names. For example, the fully qualified name of class Object in package java.lang is representated as java/lang/Object. In the method area, fully qualified names can be represented in whatever form and data structures a designer chooses.
Every java object reference knows its class at runtime; this so-called "run-time type information" is used in code like this:
if (obj instanceof class1) {
// true!
}
You can also access the class of an object through obj.getClass(). This will return class1.class, an object of class Class<class1>. See the Object.getClass method.
(Note that if your class is parameterized, as class1<T>, the type of T will not be stored at runtime, due to "erasure".)
I don't know whether the class information is stored with the pointer or with the data; it's probably implementation-specific in the jvm; but it hardly matters from a practical standpoint. (So either answer 1 or 2, or both, is "yes").
The answer to 3 is that, as far as a java programmer is concerned, the run-time type information is encapsulated in an object of class Class. Under the covers, a JVM may implement this in one way or another.
Answering your question:
No, it doesn't. Reference is just a reference, i.e. some address in heap, where corresponding object is stored. There is no need to store duplicate information about reference type in reference itself, because actually real variable, which contains its reference address could be of various class types.
Very strange question. Of course, yes, it does. Furthermore, this "part of heap" is an object, which contains this particular class description. Any Class object contains information about full name of that class, which is described by it.
It is not defined as how it looks logically, if you mean its structure:
2.7 Representation of Objects:
The Java virtual machine does not mandate any particular internal
structure for objects.
But if we are talking about information about class type - yes, it is just a String object, because "type" of Class object (which it is represent) is just a name of corresponding class.
This is one of the scheme in which the JVM can store the information of the class for the check at runtime using instanceOf.
Every Java virtual machine must have the capability to determine information about its class, given only a reference to an object. This is needed for many reasons, including type-safe casting and the instanceof operator.
This is one way in which a Java virtual machine implementation could
associate class information with the instance data for an object. In
this figure, a native pointer to a data structure containing class
information is stored along with the instance variables for an object.
The details in which the various ways a JVM could connect an object's
data with its class information are beyond the scope of this article.
The important thing to understand here is that class information will
in some way be associated with the instance data of objects, and that
the instance data includes fields for an object's class and all its
superclasses.
Artima post on Object initialization
So when you do instanceOf check the information about the class is accessed via this pointer. But again do keep in mind that the exact implementation about the storage of class information may be implementation specific.

What exactly is an instance in Java?

What is the difference between an object, instance, and reference? They say that they have to create an instance to their application? What does that mean?
An object and an instance are the same thing.
Personally I prefer to use the word "instance" when referring to a specific object of a specific type, for example "an instance of type Foo". But when talking about objects in general I would say "objects" rather than "instances".
A reference either refers to a specific object or else it can be a null reference.
They say that they have to create an instance to their application. What does it mean?
They probably mean you have to write something like this:
Foo foo = new Foo();
If you are unsure what type you should instantiate you should contact the developers of the application and ask for a more complete example.
"instance to an application" means nothing.
"object" and "instance" are the same thing. There is a "class" that defines structure, and instances of that class (obtained with new ClassName()). For example there is the class Car, and there are instance with different properties like mileage, max speed, horse-power, brand, etc.
Reference is, in the Java context, a variable* - it is something pointing to an object/instance. For example, String s = null; - s is a reference, that currently references no instance, but can reference an instance of the String class.
*Jon Skeet made a note about the difference between a variable and a reference. See his comment. It is an important distinction about how Java works when you invoke a method - pass-by-value.
The value of s is a reference. It's very important to distinguish between variables and values, and objects and references.
When you use the keyword new for example JFrame j = new JFrame(); you are creating an instance of the class JFrame.
The new operator instantiates a
class by allocating memory for a new
object and returning a reference to
that memory.
Note: The phrase "instantiating a class" means the same thing as
"creating an object." When you create
an object, you are creating an
"instance" of a class, therefore
"instantiating" a class.
Take a look here
Creating Objects
The types of the Java programming
language are divided into two
categories: primitive types and
reference types.
The reference types
are class types, interface types, and
array types.
There is also a special
null type.
An object is a
dynamically created instance of a
class type or a dynamically created
array.
The values of a reference
type are references to objects.
Refer Types, Values, and Variables for more information
I think that Object = Instance. Reference is a "link" to an Object.
Car c = new Car();
variable c stores a reference to an object of type Car.
Computer c= new Computer()
Here an object is created from the Computer class. A reference named c allows the programmer to access the object.
The main differnece is when you say ClassName obj = null; you are just creating an object for that class. It's not an instance of that class.
This statement will just allot memory for the static meber variables, not for the normal member variables.
But when you say ClassName obj = new ClassName(); you are creating an instance of the class. This staement will allot memory all member variables.
basically object and instance are the two words used interchangeably.
A class is template for an object and an object is an instance of a class.
"creating an instance of a class" how about, "you are taking a class and making a new variable of that class that WILL change depending on an input that changes"
Class in the library called Nacho
variable Libre to hold the "instance" that will change
Nacho Libre = new Nacho(Variable, Scanner Input, or whatever goes here, This is the place that accepts the changes then puts the value in "Libre" on the left side of the equals sign (you know "Nacho Libre = new Nacho(Scanner.in)" "Nacho Libre" is on the left of the = (that's not tech talk, that's my way of explaining it)
I think that is better than saying "instance of type" or "instance of class". Really the point is it just needs to be detailed out more.... "instance of type or class" is not good enough for the beginner..... wow, its like a tongue twister and your brain cannot focus on tongue twisters very well.... that "instance" word is very annoying and the mere sound of it drives me nuts.... it begs for more detail.....it begs to be broken down better. I had to google what "instance" meant just to get my bearings straight..... try saying "instance of class" to your grandma.... yikes!
The Literal meaning of instance is "an example or single occurrence of something." which is very closer to the Instance in Java terminology.
Java follows dynamic loading, which is not like C language where the all code is copied into the RAM at runtime. Lets capture this with an example.
class A
{
int x=0;
public static void main(String [] args)
{
int y=0;
y=y+1;
x=x+1;
}
}
Let us compile and run this code.
step 1: javac A.class (.class file is generated which is byte code)
step 2: java A (.class file is converted into executable code)
During the step 2,The main method and the static elements are loaded into the RAM for execution. In the above scenario, No issue until the line y=y+1. But whenever x=x+1 is executed, the run time error will be thrown as the JVM does not know what the x is which is declared outside the main method(non-static).
So If by some means the content of .class file is available in the memory for CPU to execute, there is no more issue.
This is done through creating the Object and the keyword NEW does this Job.
"The concept of reserving memory in the RAM for the contents of hard disk (here .class file) at runtime is called Instance "
Objects, which are also called instances, are self-contained elements of a program with related features and data. For the most part, you use the class merely to create instances and then work with those instances.
-Definition taken from the book "Sams Teach Yourself Java in 21 days".
Say you have 2 Classes, public class MainClass and public class Class_2 and you want to make an instance of Class_2 in MainClass.
This is a very simple and basic way to do it:
public MainClass() /*******this is the constructor of MainClass*******/
{
Class_2 nameyouwant = new Class_2();
}
I hope this helps!
Instance variable: It must be attached to the object. Instance variables in this class can only be used after instantiating the class
public class Test{
static int a = 13;
int b = 14;
public static void main(String[] args){
int d = new Test().b;
System.out.println(d);
}
}
Instance = memory is allocated at run time for anything that is called instance
Object = memory is allocated at run time for class that is called object

Categories