class A{
int a=10;
public void show(){
System.out.println("Show A: "+a);
}
}
class B extends A{
public int b=20;
public void show(){
System.out.println("Show B: "+b);
}
}
public class DynamicMethodDispatch {
public static void main(String[] args) {
A aObj = new A();
aObj.show(); //output - 10
B bObj = new B();
bObj.show(); //output - 20
aObj = bObj; //assigning the B obj to A..
aObj.show(); //output - 20
aObj = new B();
aObj.show(); //output - 20
System.out.println(bObj.b); //output - 20
//System.out.println(aObj.b); //It is giving error
}
}
In the above program i'm getting Error wen i try invoking aObj.b.
1.why i'm not able to acess that variable through the aObj though it is refering to class B??
2. why i'm able to acess the method show()?
You have to distinguish between the static type of aObj and the runtime type of aObj.
Code such as
A aObj = new B();
results in an aObj variable with static type A and runtime type B.
The compiler will only bother too look at the static type when deciding what to allow or not.
To your questions:
1.why i'm not able to acess that variable through the aObj though it is refering to class B??
Because there is (in general) no way for the compiler to know that aObj will refer to a B object at runtime, only that it will refer to some form of A object. Since .b is not available on all A objects, so the compiler will think "better safe than sorry" and disallow it.
2.why i'm able to acess the method show()?
Because this method is available in all A objects (if it's not declared in the subclass, it is still inherited from A).
aObj is a local variable of type A. A has no member called b, that's only in your subclass B. If you want to use b, you need to declare a variable of type B, but of course you can only assign it instances of B (or subclasses if there are any).
A declares a method show(), but you override the implementation in your subclass B.
This behavior is known as virtual method invocation, and it is an important aspect of polymorphism in Java. You should have a look at this tutorial.
class A{ // class A has variable a and method show();
int a=10;
public void show(){
System.out.println("Show A: "+a);
}
}
class B extends A{ //class B inherits variables and methods of A.
// so class B has variable a, b and show(). Also, show is overridden by class B.
public int b=20;
public void show(){
System.out.println("Show B: "+b);
}
}
since A doesn't have variable b inside it, even when u are passing B to A, you still have A object which does not have variable b inside it. So, trying to access b will give you compile time error.
in case of show(), A and B both have this method, so what you are doing here is actually overriding it at runtime. This is nothing but Polymorphism. So since A already has method show(), and it is overridden later by B,
A a = new B();
a.show();
this will run the show() method of B at runtime.
Methods and fields have different polymorphic behaviour.
The method that will be called is the method of the run time type of the instance
aObj=new B(); //new B()
The field that will be called is the field of the type of reference that you declared
A aObj = new A(); // A aObj
The following would work even is there was no show() method in A.
aObj = new B();
aObj.show(); //calls B's show()
Related
This question already has answers here:
Does polymorphism apply on class attributes in Java?
(8 answers)
Closed 4 years ago.
I have the following program :
class A{
int b = 50;
}
class B extends A{
int b = 20;
}
public class Maini{
public static void main(String[] args){
A a = new B();
System.out.println(a.b);
}
}
and the result is 50 and I would like to know why?
before I run the code I am pretty sure that the result should be 20.
This has nothing to do with how constructors work.
Note that the member variable b in class B does not override the member variable b in class A. Only non-static, non-private methods can be overridden. Member variables cannot be overridden.
If you have an instance of class B, then it actually has two member variables called b: one in the superclass (A) part of the object, and one in the subclass part (B).
The reason that you see the value 50, which is the value of b in the A part of the object, is because the variable a in the main method is of type A. If you change this to B, you'll get 20:
B a = new B(); // instead of A a = ...;
In the statement
A a = new B();
You are calling Bs constructor in an object of type A
In your program, you have given no constructor to B, so it looks to A.
In A, the value of int b is 50 and an object is of type A, hence the value is chosen as 50
If you had a constructor in B e.g.
B() { b = 20;}
the value would be 20.
You think that you are creating a B but you have not written any constrcutors for the class B so it looks to the super() constructor which is it's parents (A). So you now have an object of A. If you are curious about why A's object isi being created while there is no constructor to it too. A calls to it's super constructor too which is Java's Object Class's constructor.
I hope that I could make this point clear.
use a intellitrace enabled IDE for better experience of coding.
1st of all you'l hav a default constructor if you are not imposing on it.
Secondly you are defining an object of type 'A' not 'B'. if you want the output as 20 then you hav to include this B() {int b = 20;}.
Here in this code Sniplet there is no constructor in Any class.
So JVM will create no argument default constructor in all classes.
While you are Running this then .
In the below code you
a is referring class A and having object of class B
A a = new B();
So here the Object a will have class A 's variable value.
and Class B object value as its calling Class B 's default constructor(new B();)
If Class A and B have same Method like below Example:
class A{
int b = 50;
void method(){
System.out.println("Method of A class");
}
}
class B extends A{
int b = 20;
void method(){
System.out.println("Method of B class");
}
}
public class Maini{
public static void main(String[] args){
A a = new B();
System.out.println(a.b);
a.method();
}
}
Then a.method() will print
50
Method of B class
as a is have Class B 's object.
When you write A a = new B() the object a is type A. This is why you're getting b = 50. If you want to get b = 20, you need to declare a as a B class
Hope it's clear enough.
Best
class A{
int foo=10;
}
class B extends A{
int foo=10;
}
class Test{
public static void main(String [] args){
A a=new B();
System.out.println(a.foo);
//System.out.println(a.getClass());
}
}
In this case 10 is output. If I am not wrong, then this is because the a variable is of type A and variable assignment is static binding, and static binding is done at compile time by looking at the type of the variable. Since here a is of type A, then A's int foo is called. However when I call
System.out.println(a.getClass());
then this gives class B, that is a is of type B. I am confused about this. Kindly explain to me a is of which type and how A's int foo is printed.
But by looking at this code
class A{}
class B extends A{}
class Test{
public static void main(String [] args){
B b=new B();
A a=b;
B b1=(B)a; // compiles and run fine (a is of type B)
}
}
How is this possible? What's happening here? First b is of type B then in the second line a becomes of type A, as A a=.. is written but a.getClass() gives that it is of type B. How? If a is of type B then why is it calling A's int foo in the first example? Kindly explain both examples.
Also, does type casting change references or do any other stuff?
An important thing to realise is that Java only has primitive and reference variable types. This means when you write
A a =
The a is just a reference to an object (or null) not an object.
When you do
A a = new B();
there is no cast here, no work is done, no object is harmed or changed.
When you call an instance method on a class, it calls the method for the class of the object.
Object o = new B();
assert o.getClass() == B.class;
a longer example
B b = new B();
A a = b;
assert a == b; // always true as they point to the same object.
assert b.getClass() == B.class;
// so it makes sense that since a == b
assert a.getClass() == B.class;
type casting change references or do any other stuff?
It changes the type of the reference and it doesn't do other stuff like change the type of the object.
methods follow inheritance, however fields follow the type of the reference as a field cannot be overridden, it can only be hidden.
B b=new B(); A x=b; B b1=(B)x; // compiles and run fine (x is of type b) in this line when x is of which type
correct and you wouldn't be able to (B)x unless x was a reference to a B The variables x is an A which means it must point to an A object or a sub-class of a A e.g. B you can write
B b = new B();
A x = b;
assert x == b; // they still point to the same object.
B b1 = (B) x;
assert b1 == b; // same object
assert x == b1; // same object.
No new objects are created, nor is the object changed.
Quite simple why it does print the foo of A, because a is defined as A. Since there is no overriding for variables you are simply accesing the variables which are accesible for the type the variable is declared, which is A in this case.
public static void main(String[] args) {
A a = new A();
System.out.println(a.foo); // prints the foo of A, since a is of the type A
A b = new B();
System.out.println(b.foo); // prints the foo of A, since b is of the type A
B c = new B();
System.out.println(c.foo); // prints the foo of B, since c is of the type B
}
In the end it´s called shadowing what you are doing there. Your class B has a variable with the same name as A. Since they are not overridable you are able to hide foo of A, if your variable is of the type B, where you are accessing foo of B
Your question is related to Javas polymorphic behavior and dynamic (late) vs. static (early) binding.
The access to all the member variables in Java follows static binding. That means you have no polymorphism in this case. Instance Methods are dynamically bound. The instance method used for an invocation will be determined by the class of the object, not by the reference type. For example:
public class Main {
static class A{
String foo="A";
public String getFoo() {
return foo;
}
}
static class B extends A{
String foo="B";
#Override
public String getFoo() {
return foo;
}
}
public static void main(String[] args) throws Exception {
A a=new B();
System.out.println(a.foo); // prints A
System.out.println(a.getFoo()); // prints B
System.out.println(a.getClass()); // prints Main$B
}
}
Late binding
Early Binding
Polymorphism
object a2 is of type A but references an object of class C. So, a2 should be able to access m3(). But, why is it not happening? If m3() method had been defined in class A, then the code would run fine
class A {
int var = 7;
void m1() {
System.out.println("A's m1 ,");
}
void m2() {
System.out.println("A's m2 ,");
}
}
class B extends A {
void m1() {
System.out.println("B's m1 ,");
}
}
class C extends B {
void m3() {
System.out.println("c's m3 ," + (var + 6));
}
}
class Mixed {
public static void main(String[] args) {
A a = new A();
B b = new B();
C c = new C();
A a2 = new C();
a2.m1();
a2.m2();
a2.m3();
}
}
A a2=new C();
That means you can access only the members of Class A and implementations of Class C, if any overridden.
Now m3 is not a member of A. Clear ?
When you write this line
A a2=new C();
a2 will only ever be able to access methods defined in Class A.
Even though a2 refers to an instance of Class C, it cannot invoke methods defined only in C.
However, if you had the following:
class A {
void m3() {
System.out.println("in A");
}
}
class C extends A {
void m3() {
System.out.println("in C");
}
}
...
A a2 = new C();
a2.m3();
would output
in C
In this case, the m3() method is being overridden and the method invoked will be determined by the type of the instance which a2 refers to (i.e. C).
I would take a look at the Java tutorials here: http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html
If you use a reference of the parent / superclass and try to invoke a method on the subclass, then that method should be defined in the parent / superclass. i.e, what methods you can call on the object(rhs) depends on the lhs (reference type).
You see the subclass C as an instance of A because an A does not have the function m3 that a C has.
A a2 = new C();
So here, you can access only the methods in C that are inherited from A. You basically see it as an A. If you wanted to call the methods in C, you would have to cast it to C, so you'd have to do something like this:
if(a2 instanceof C)
{
C castedA2 = (C)a2;
castedA2.m3();
}
Compiler checks reference of object which is invoking a method...
In your case A a2=... is what compiler can see, and it finds that there is no m3() method defined in A class. Hence code will not compile.
Note that,
While invoking method at runtime, JVM refers the object referenced by the Reference. In your case Reference of class A is referring Object of class C.
Read more at : Polymorphism in Java
class A {
int super_var = 1;
}
class B extends A {
int sub_var = 2;
}
public class Demo{
public static void main(String []args){
A a = new B();
System.out.print(a.sub_var); //compile error
}
}
why this will end with a compile error ? reference (a) referencing to an Object of B it has sub_var so why is it restricted ? why reference (a) can access only the fields in A ?
Let's say you have these classes:
public class Animal() {
// ...
}
public class Fish extends Animal() {
public void swim() {...}
}
If you declared an Animal:
Animal x = new Fish();
and you called the swim() method
x.swim();
Would you expect it to work? I don't think so, because not every animal can swim. That's why you have to explicitly specify that the animal x is a Fish:
((Fish) x).swim();
In your case, if you wanted to call that method, you should specify (technically, it's called cast) the type:
System.out.print(((B)a).sub_var);
Note:
This works similar for methods and variables. I used a method in the example since it's more illustrative.
Edit:
Let's see this example:
Animal x;
if (some_condition)
x = new Fish();
else
x = new Cat();
x.swim();
This restriction exists, because Java won't know if, at execution time, the object assigned to x will have the method swim(). So to avoid this, you have to cast to the respective type to call a method that doesn't exist in superclass.
At first it does sound like it should work. (And in some languages it probably does.) But think about this example:
public class Demo {
public static void main(String []args){
A a = new B();
print( a );
}
public static void print( A arg ) {
System.out.print(arg.sub_var); //compile error
}
}
This functionally does the same thing but the print is in another method. If your version worked, this one could be expected to work too.
But what if someone then does this?
Demo.print( new A() );
This should fail because A doesn't have a sub_var. It would have to throw some kind of runtime error instead.
So the design decision in Java was not to allow this and if you declare a local variable/field/method parameter as type A, then you can only access things that every object that is either A or a subclass is guaranteed to have.
If you want to access more, you need to cast it to the subclass, which will throw an exception if you try it on an object that doesn't fit.
A a = new A();
System.out.print(((B)a).sub_var); //ClassCastException is thrown here
You can not access B members with the reference of Parent object A.
Instead change your println statement like below to access,
System.out.print(((B)a).sub_var);
Is there a variable called sub_var in the parent class ? No. That is why you get the error -
sub_var cannot be resolved or is not a field
See this
System.out.print(a.super_var); //okay
System.out.print(a.sub_var); //compile error
you create an object of type B and assign it to a variable of type A. The type A does not declare sub_var. This field is declared only in type B. the compiler only sees what is declared in type A, although the variable is instantiated to an object of type B.
If you want to access sub_var you would have to cast a to B.
System.out.println( ((B)a).sub_var);
The sub_var is in class B, so you can only access through a reference of class B. To the compiler A a = new B(); means a is an instance of class A.
Ok.. So,
When you have a hierarchy of classes such as
public class A {...}
and,
public class B extends A {...}
...When you create objects, what is the difference between:
A object = new A();
A object = new B();
B object = new B();
Thank you for your time.
public class A
{
public void methodA(){}
}
public class B extends A
{
public void methodB(){}
}
I hope this can demonstrate the difference.
A obj = new A();
a.methodA(); //works
A obj = new B();
obj.methodA(); //works
obj.methodB(); //doesn't work
((B)obj).methodB(); //works
B obj = new B();
obj.methodA(); //works
obj.methodB(); //works
A object = new A();
You are creating an A instance in a reference of type A. You may can access only A methods/properties and parents methods/properties.
A object = new B();
You are creating B instance in a reference of type A. In this way object could behave in a polymorphic way, for example if you make object.method() and method is overriden in B then it will call this override method. You have to take care in not to break the Liskov Substitution Principle. You may can access only A methods/properties and parents methods/properties. This is the preferred way when you only need supertype contract.
B object = new B();
You are creating a B instance in a reference variable of type B. You may can access only B methods/properties and parents methods/properties.
A line like
A var = new B();
is kind of a shorthand for two separate steps.
A var; // (1) Make a variable of TYPE A.
var = new B(); // (2) Make an object of CLASS B, that from now on may be
// referred to by the variable var.
So a variable has a TYPE, and an object has a CLASS. Often they match up. The type of a variable is often actually a class, although not necessarily. It's important to understand the difference between the type of a variable, and the class of the object that the variable refers to.
An object typically belongs to more than one class. If class B extends class A, that means that all objects of class B are also objects of class A. And all objects of any class at all are also objects of class Object. In other words, when we say that an object is a B, that's more specific than saying it's an A. Just like when we say that Yogi is a bear, that's more specific than saying Yogi is an animal, because all bears are animals.
So a variable of type A can indeed refer to an object of class B, if A is a class that B extends. But if you've got a variable of type A, you can't use it to do things that are specific to objects of type B. For example, suppose class A has a method called display() and class B has a method called explain(). The compiler will let you call display() on a variable of type A, but it won't let you call explain(). If it did, it would be risking trying to call explain() on an object that's not actually a B, which would fail.
So whenever there are methods that class B defines, you'll need a variable of type B in order to be able to call them. Of course, you can also use that same variable to call the methods that are defined in class A. In a sense then, if class B extends class A, then a variable of type B is more powerful than a variable of type A - you can do more stuff with it.
So the question arises - why would I ever want to write
A var = new B();
when a variable of type B would be more powerful than var in this example?
The short answer is that it communicates to people looking at the code. It says, "yes, I know this variable refers to a B, but I actually only intend to use the methods provided by class A. This can actually be helpful to someone trying to understand your code, or to maintain it.
There are also cases where it can make a real difference to method calls involving that variable. Suppose there's another class C, which has two methods with the same name but slightly different signatures, like this.
public class C {
public void process(A arg){
// Do some stuff
}
public void process(B arg){
// Do some other stuff
}
}
In this particular case, the version of process that gets called depends on the type of the variable, not the class of the object. So if you write
C processor = new C();
A var = new B();
processor.process(var);
this will call the first version of process - the one with A in the signature. Because of the type of the variable. But if you write
C processor = new C();
B var = new B();
processor.process(var);
this will call the second version of process - the one with B in the signature.
A object = new A();
object of type A (you can access fields or method from A)
A object = new B();
object of type A (you cannot access fields or method from B, only from A)
B object = new B();
object of type B (you can access fields or method from A and B)
A object1 = new A();
A object2 = new B();
B object3 = new B();
object1 is declared as a reference to an A object. Since class B extends class A, it could be set to either or (new A() or new B() would be valid).
object2 is declared as a reference to an A object, but is actually a B object. Say the B class has a method called eatFood(). If you tried to access that method with object2.eatFood(), the compiler would throw an error because the eatFood method is only in the B class. Even though the object is actually a B object, the compiler thinks it is an A object due to the type declaration. To access the eatFood method, you would have to typecast it: ((B)object2).eatFood().
object3 is simply a reference to a B object, and in reality IS a B object. It could access A methods as well as B methods.
A object = new B();
This declares that object will refer to an object of class A or any of its subclasses (when it isn't null). The compiler will treat it as an object of type A, so you can only access methods and fields that are declared for A (or one of its superclasses). It also means that you can later assign it to any other object that is of class A or a subclass:
A object1 = new B();
B object2 = new B();
// reassign later
object1 = new A(); // legal
object2 = new A(); // ILLEGAL
class C extends A { ... }
object1 = new C(); // legal
object2 = new C(); // ILLEGAL
So the initial declaration declares object as having type A. But its initial value is an object of type B, which is OK because B is a subclass of A.
That should explain the difference between your second and third examples. The difference between the first and second is simply that (at run time) the first creates a new object of type A and the second creates a new object of type B.