In Java, when you pass an object to another object (eg. pass object1 to object2), would object 2 inherit all of object1s properties such as methods and variables, what exactly happens?
-
6What do you mean by "pass an object to another object" as this is a very ambiguous statement? Please describe in greater detail just what you're trying to do and show some code.Hovercraft Full Of Eels– Hovercraft Full Of Eels2015-01-10 18:20:12 +00:00Commented Jan 10, 2015 at 18:20
-
Show an example of exactly what you mean.Kon– Kon2015-01-10 18:21:22 +00:00Commented Jan 10, 2015 at 18:21
-
I think this is headed toward this question: stackoverflow.com/questions/40480/…Jason Sperske– Jason Sperske2015-01-10 18:21:45 +00:00Commented Jan 10, 2015 at 18:21
-
Inheritance only happens when Class2 extends Class1.Hovercraft Full Of Eels– Hovercraft Full Of Eels2015-01-10 18:21:58 +00:00Commented Jan 10, 2015 at 18:21
-
@JasonSperske: I'm not sure. The question is very very vague to me. To the original poster, please go through the tour, the help center and the how to ask a good question sections to see how this site works and to help you improve your current and future questions, thereby getting better answers.Hovercraft Full Of Eels– Hovercraft Full Of Eels2015-01-10 18:22:25 +00:00Commented Jan 10, 2015 at 18:22
2 Answers
In Java Inheritance is a different concept compared to Passing objects to other object.Actually you cannot pass an object to other object, you can pass object to methods.
Check this To Pass Objects to functions
You can access Instance methods/Instance Variables using Object.
class SuperClass{
public void method(){
//....
//...
}
}
public class Example{
public void example(SuperClass object)
{
//you cannot directly call super class method
//if you want to call then use Object
object.method()
}
}
In Inheritance you can access Instance Variables/ Methods with out using object to that class.
class SuperClass{
void method(){
//....
//...
}
}
class Example extends SuperClass{
public void exampleMethod()
{
//You can directly call superclass method here
method()
}
}
For more details on Inheritance check
2 Comments
IS-A Relationship
Inheritance can be defined as the process where one
object acquiresthe properties of another. With the use of inheritance the information is made manageable in a hierarchical order.
This means you are able to access super class member and method in your subclass.
class A{
int a;
}
class B extends A{
}
int a get inherited in class B so you can use it in class B Read more
You can not pass one object to another object.
Software objects communicate and interact with each other in two ways:
1. By calling (or invoking) each other's methods
2. By directly accessing their variables.
4 Comments
add(a,b), you can pass (objects) but you cannot pass classes through method.