Sample code:
PrintMethod.java
public class PrintMethod {
void print (String s) {
System.out.print(s);
}
}
PrintS.java
class PrintS {
public static void main(String[] args) {
PrintMethod pm = new PrintMethod(); //i know this is how you make a new object, but
pm.print("Hello");
}
}
Where is the object here? I've looked all over the internet, but what my teacher is telling me is different from what I found. Help?
And what then is the difference between an object and a class? If PrintS and PrintMethod are objects as well? I thought an object was an instance of a class? I'm so sorry, I just need this topic to be crystal clear.
I think the best answer you can get can be found in the official docs:
The new operator instantiates a class by allocating memory for a new
object and returning a reference to that memory. The new operator also
invokes the object constructor.
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.
The new operator returns a reference to the object it created.
In your case, pm is a reference to an object of type PrintMethod. When you do pm = new PrintMethod() you are constructing a new object.
See the part of Using Objects in the official docs.
Clarification: When you say class, you usually refer to the code, it is simply a piece of code. But when you say object, you mean an instance of the class. Every object "belongs" to a class.
For example, consider a class named Car. All cars have wheels. An instance of Car would be a specific car, say toyota. So toyota is now an instance of Car.
An Object is the blueprint of a Class that gets created in Heap Memory. To get access to those objects we use references in Java Code.
So we don't directly access objects in Java Code. It is the reference that we access and use.
In your case pm is just an reference to a instance of PrintMethod placed in Heap memory. But "Hello" is a literal instance of a String that gets created in String pool.
PrintMethod pm = new PrintMethod();
the left side part is called as Declaration and the right side part is called reference,where new which allocated the memory>
We can define Object in 4 ways .
1) An Object is an Instance of a class ( Instance is nothing but allocating sufficient amount memory space for the data members and methods of a class )
2) Each and every class variable are also known as objects .
3) Blue print of a class is known as an object .
4) Each and every grouped Item is known as an object ( You know a grouped item is a variable which allows us to store multiple values of same type or different type or both at once )
So.,
Here i will give a small explanation about what is a object .
dear friend " Have you seen a Tree" ?????
Most of the people say that they have seen a tree . But Answer is Nooooo....
You never seen a tree but you have seen Types of tree like Banana Tree, Apple tree... etc
So here if you understand there is a very good beauty in it .
So a tree is a plan and Types of trees are Objects . So, Now tell me does a tree exists . Nooo its just a plan and based on that plan types of trees can be planted .
A class is a blue print and based on a class many objects can be created . So Always remember that "A class has Logical Existence " and "an Object has Physical Existence "
Objects are building blocks of an OO program. A program that uses OO technology is basically a collection of objects.
Each Object is made up of the Data & Behavior.
Object Data: the Data stored within an object represents the state of the Object. In OO programming terminology, this data is called Attributes.
Object Behavior: The behavior of an object is what the object can do. In OO programming terminology, these behaviors contained in methods, and you invoke a method by sending a message to it.
Also i agree with the "Maroun Maroun."
Related
The Java Language Specification says:
An object is a class instance or an array.
And it also says:
arrays [...] may be assigned to variables of type Object
But the part that confuses me is:
The class Object is a superclass of all other classes
If arrays may be assigned to variables of type Object, then it must mean that arrays can be Objects (not only behave as, but to be instead). Then it means that an array is a class instance, which does not seem to be consistent with the first quote (if it were, then why would it be listed as a different thing?).
How can all this fit together?
There is no contradiction.
An array is also an Object, albeit a special kind of Object.
It is like saying: An bird is also an animal, albeit a special kind of animal.
You can convince yourself by compiling and running the following Java code.
String[] arrayOfStrings = { "bla", "blah" };
// examine the class hierarchy of the array
System.out.println("arrayOfStrings is of type "
+ arrayOfStrings.getClass().getSimpleName()
+ " which extends from "
+ arrayOfStrings.getClass().getSuperclass().getSimpleName());
// assingning the array to a variable of type Object
Object object = arrayOfStrings;
The output will be
arrayOfStrings is of type String[] which extends from Object
Arrays are special classes provided to you by Java itself. All of them inherit from common superclass Object. As they inherit from Object they of course can be used anywhere where Object is expected. Instances of arrays are indeed instances of those classes. One can even reference array classes as they do with other classes' literals:
Class<int[]> intArrayClass = int[].class;
I see no conflict.
This can be useful https://docs.oracle.com/javase/specs/jls/se7/html/jls-10.html#jls-10.8
Yes... and no. It is true, indeed, that new Object[100] instanceof Object → true, but this is missing the true nature of arrays in Java. Arrays are objects (lowercase), but not Objects (capitalized). Being objects, for example, you have to use the new operator to allocate space for them.
However, the Java Language Specification is right to say that "An object is a class instance or an array", because arrays are fundamentally different from a regular Object. They are inherited from languages such as C++, that were much more deeply rooted in the low-level architecture of computers.
"arrays [...] may be assigned to variables of type Object" only because Java provides an interface for us, programmers, to refer to arrays as Objects. In fact, the JLS says:
All methods of class Object may be invoked on an array
Which of course is true, but it does not logically imply they are Objects. Arrays are not true Objects; therefore, they are not true class instances, and therefore the sentence "The class Object is a superclass of all other classes" doesn't apply here.
All in all, Java is not a pure Object-Oriented programming language (primitives are not objects, for example, but they are nonetheless present in Java). And arrays are a language feature that Java includes that behave as if they were class instances of the Object class, but are not actually class instances of it.
[This is my attempt at summarising the main points made here. Thanks a lot to all of you for your ideas, and feel free to add more!]
The class Object is a superclass of all other classes
All classes in Java extend Object. The class name is actually Object (proper name capitalized). It's why all classes have the method toString() and hashCode(), because they all inherited it from Object.class
An object is a class instance or an array.
An object (lowercase, not a proper name) is the instance generated by the new keyword. ie: File is a class and when you call new File() you just made a File object. I honestly think they should have called it a class instance. (clarification: I wish they never called an instance an object)
arrays [...] may be assigned to variables of type Object
Object[] is an array that can contain instances of type Object.
Object[] obj = new Object[100];
obj instanceof Object evaluates to true.
Your second link also says:
All methods of class Object may be invoked on an array.
So from a dev's POV, at least, it's an Object though there is no java.lang.Array (that is exposed to us) it has been instanced from.
A second indication is that arrays are also stored on the heap.
for the following code:
class Parent {
public void say(){
System.out.println("Parent");
}
}
class Child extends Parent{
public void say(){
System.out.println("Parent");
}
}
class Test {
public static void main(String[] args){
Parent p = new Child(); // What does the compiler check
p.say();
}
}
The following questions have always confused me.
1. what exacly is happening during compile time? How does the comiler know that Parent p = new Child() is a valid code as no object has been created at compile time?
2. what exactly is hapenning at runtime? How is memory allocated
3. The implicit call to parent's constructor creates an Parent Object. A child object is also created. How is it stored and how does jvm use this for method resolution.
4. Lastly, is JVM hardcoded not to ovverride static methods and variables or there is some other reason. Why can't we use Runtime objects instance method() why not runtime objects variables
Where can I read more on these topics?
Thanks
exactly is happening during compile time? How does the comiler know that Parent p = new Child() is a valid code as no object has been created at compile time?
Well, whole books are written about that subject. In essence, the compiler parses the input source, and it finds that assignment:
Parent p = new Child();
And now the compiler does two things:
it checks what it can find out about the types on both sides of the assignment
thus it finds: the left hand side needs an object of type `Parent``
it also looks at the right hand side, to understand the (potential) result types that comes out of that expression
So, in the end, the compiler will see: "I need a Parent ... and I get something that is a Child." Then the compiler has to check if an instance of Child satisfies "I need a Parent". And obviously: it does.
what exactly is happening at runtime? How is memory allocated
Again, whole books are written about that. See here for example.
The implicit call to parent's constructor creates an Parent Object. A child object is also created. How is it stored and how does jvm use this for method resolution.
The JVM "simply" knows two things:
when reserving the memory for a Child object, it needs to also consider the memory required for any super class fields
so, in the end, you simply have one area of memories large enough to hold all fields of all parent classes, down to the Child class itself
Finally: static methods are inherented, but yes, there is no polymorphism for them in Java. That is simply a design point of the language, and the semantics that are defined for Java. It could be done differently, but 20+ ago, the fathers of Java decided to do it like they did.
Reading "Thinking in Java" by Bruce Eckel at the moment. Reached "this" keyword point. It's not clear for me how really objects and "this" work. Bruce Eckel in his book says:
If you have two objects of the same type called a and b, you might wonder how it is that you can call a method peel( ) for both those objects:
//: initialization/BananaPeel.java
class Banana { void peel(int i) { /* ... */ } }
public class BananaPeel {
public static void main(String[] args) {
Banana a = new Banana(),
b = new Banana();
a.peel(1);
b.peel(2);
}
} ///:~
If there’s only one method called peel( ), how can that method know whether it’s being called for the object a or b?
To allow you to write the code in a convenient object-oriented syntax in which you “send a message to an object,” the compiler does some undercover work for you. There’s a secret first argument passed to the method peel( ), and that argument is the reference to the object that’s being manipulated. So the two method calls become something like:
Banana.peel(a, 1);
Banana.peel(b, 2);
So, when we create an object it has it own methods copied from the class.
A obj = new A();
obj.callMethod(); //<-- object uses it's own method, not the class, right?
And according to the book the methods of a class are shared somehow between all
the objects created from this class.
How does this mechanism work in the result?
I don’t get this part:
If you have two objects of the same type called a and b, you might wonder how it is that you can call a method peel( ) for both those objects.
If there’s only one method called peel( ), how can that method know whether it’s being called for the object a or b?
What does it mean “only one method called peel()”
We have all the methods from the class created for each object. So we just call the method from the object.
What did Bruce Eckel mean?
If you and I both laugh when something is funny, you may say that we share the ability to laugh.
I am thinking of sharing methods between instances of a class in much the same way. Bananas share the property that they can be peeled. The Banana class specifies what Banana objects are and what they can do. Some have described the class as a template for creating objects or a rubber stamp for stamping them. All bananas can be peeled, but the programmer still decides which ones s/he actually peels, and when. In programming terms: The Banana class specifies that every banana has a peel method, and what that method is.
When Eckel does a.peel(1); he’s specifying that he is peeling banana a (and not banana b just yet). As far as I am concerned, this all you as an object-oriented programmer need to know to use bananas and their methods.
Classes, objects and instance methods are described in many ways in many places. You may see if it helps you to search for other descriptions to supplement the one by Eckel.
This question already has answers here:
What is polymorphism, what is it for, and how is it used?
(29 answers)
Closed 6 years ago.
Let's say I have a piece of code:
class one
{
String one = "First";
}
class sec extends one
{
String sec = "Second";
}
class num
{
public static void main(String[] args)
{
one o = new one();
sec s = new sec();
one oo = new sec();
// the object will be of that class for which we are providing the reference
// then what is the use of the constructor
sec s = new one(); // this is not working
System.out.println(o.one);
System.out.println(s.sec);
System.out.println(oo.one); # this seems right
System.out.println(oo.sec); # this is not working
}
}
I am confused by the reference and the constructor while creating the object.
I have extended the sec class to inherit from class one.
I got the meaning of first two object creation that we are referencing to the one class and creating the object same for the second object.
But what about the third object? We are using the reference of the class one and providing the constructor of the child class and I can use the third object(oo) just to refer the variable and methods of the one class not second class.
If I have to use the methods and variables of one class then I can use it with the object(o) rather than object(oo). So what is the difference between both the objects when they are behaving like each other?
one o = new one();
one oo = new sec();
I want to know the difference between these two that what are the changes come when we use the constructor of the child class rather than the base class.
This is actually one of the famous topic of discussion.
First of all there is two things known as object & reference.
Object means your actual image or actual data.
Reference means your view of object.
In terms of database, You can compare object as table & reference as view.
Let's say we have three dimensional cylinder type of object when you see it from top it just look like circle & from front it look like square (here I'm talking about identical conditions) but it's neither actually a circle nor square.
Here the actual object is your cylinder & the the images you get from seeing it from different angles is your reference.
Now come back to the actual question.
When you write one o = new one() it's actual object of one which is referenced (viewed) as a one.
Now when you write one po = new two() it's actual object of two which is referenced as two. Here there is all the components of object exist which is defined in class two. although you can not access them because of the type of reference but they are exist.
To know actual differece let discus about what happens when you write code something like this.
two t=(two)o or two tt=(two)oo
In first case Java throws exception ClassCastException. In the second case you are permitted.
In the second case your object oo is of type two, here the class two inherit the property of class one, so you can treat it as object of class one. But in first case you can not because of the same reason.
The main reason of doing this is because we don't care about all the properties of objects when we are dealing with them.
For example when you are supposed to design the code to send the mail to the list of some persons. Now think what you really required to accomplish this task? Only email id..
You actually don't care about other details which is obviously exist in the object of persons. Now you define the the one class called as Email with the method getEmail.(actually it should be interface) & you make constraints that every person should have to extend this class now every object of person contain property email although it can contain other properties but you don't have to care about that.
This question already has answers here:
Upcasting and Downcasting in java
(8 answers)
Closed 9 years ago.
I am trying to figure out why do I need Downcasting. I reread my notes from collage and found the below example.
class Student {...}
class Graduate exteds Student {
getResearchTopic(){...} // this method only exists in Graduate class.
}
We have a ref to Student class and want to access to getResearchTopic method;
Student s1 = new Graduate();
if(s1 instanceof Graduate){
((Graduate)s1).getResearchTopic();
}
Great example for Downcasting hah? My question is Why not declare s1 as a Graduate in the first place? Is there a real life example where I will have to downcast instead of using an instance of actual class?
Well, you could have declared the reference s1 to be of type Graduate. The main benefit you get by declaring the reference of super type, is the power of polymorphism.
With a super type reference, pointing to a sub class object, you can bind the same reference to multiple sub class objects. And the actual method invoked will be decided at runtime, based on what object is being pointed to. But, the main condition for this is, that method should also be defined in the subclass, else the compiler will fail to find the method declaration.
Here, you were forced to downcast, because you haven't defined the method in the super class. As compiler cannot see the definition of that method in Student class. It has no idea about what the actual object s1 points to. Remember, compiler only checks the reference type to find the meethod declaration.
In general, whenever you see yourself downcasting to a subclass in your code, it is almost always a sign a something wrong (there are some exceptions though). And you should modify your classes.
Let's see what benefit you get by using a super class reference instead of a subclass reference:
For e.g: Suppose you have another sub class of Student as:
class Phd extends Student {
getResearchTopic(){...}
}
and you also provide a definition (a default one) in Student class:
class Student {
getResearchTopic(){...}
}
Now, you create a following two objects, both being pointed to by Student reference:
Student student = new Phd();
student.getResearchTopic(); // Calls Phd class method
student = new Graduate();
student.getResearchTopic(); // Calls Graduate class method
So, with only a single reference, you get to access methods specific to subclasses.
One major implementation of this feature you can see in factory method pattern, where a single static method returns an object of different sub classes based on some condition:
public static Student getInstance(String type) {
if (type.equals("graduate"))
return new Graduate();
else if (type.equals("phd"))
return new Phd();
}
So, you can see that the same method returns an object of different subclasses.
All of the above stuffs you can do just because of one concept:
A Super class reference can refer to any sub class objects, but not vice-versa.
Say you have a method that takes a Student as a parameter. Most of the things it does are generic for all students. But if it is a Graduate there might be something else it does as well. In that case you would need to determine if the Student passed in was actually a Graduate and do some special logic in that instance.
Maybe something like this:
class StudentDAO {
public void SaveStudent(Student s) {
// Do something to save the student data to a database.
if ( s instanceof Graduate ) {
// Save their research topic too.
}
}
}
Note that doing that kind of thing is usually a poor programming practice, but sometimes it makes sense.
When you deserialize an object using the default Java deserializer, you use this code (and you use analogous code when using another deserializer, e.g. the Jackson JSON deserializer)
ObjectInputStream ois = new ObjectInputStream(in);
Object obj = ois.readObject();
You then need to cast obj to its actual type, because readObject() will always return a plain old Object - the method can't statically verify what sort of object is being read
In cases where you want to use polymorphism, it would be nice to work with Student objects, and then "downcast" to use methods specific to Graduate objects.
In general, if you have a method that works with Student objects, that method don't really know at compile-time what specific type of Student objects are passed in. Thus, at run-time, the method should check for the specific type and process accordingly.
Downcasting does help when you're trying to make generic methods. For example, I often see code that parses an XML String into an Object. The Object can then be downcast into the specific Object that you (as the coder) know it represents.
private static XStream xstream = new XStream(new DomDriver());
static {
xstream.processAnnotations(MyFirstClass.class);
xstream.processAnnotations(MySecondClass.class);
// ...
}
public static Object fromXML(String xml) {
return xstream.fromXML(xml);
}
This lets me make a very generic method which does what I want it to do in all cases. Then, when I call it, I can simply downcast the Object into what I know it's going to be. It prevents me from having to make a separate parse method for every object type and improves the readability of my code.
MyFirstClass parsedObject = (MyFirstClass) MyXMLTransformer.fromXML(xml);