Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object type declaration

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.

like image 861
JeanAlesi Avatar asked Feb 15 '23 02:02

JeanAlesi


1 Answers

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
like image 177
Cruncher Avatar answered Feb 17 '23 19:02

Cruncher