0

Whats the difference between these two?

If A is a superclass of B aka B extends A, then whats the difference between these two lines? A n = new A(); and A n = new B(); What are all the possible differences here?

30th Oct 2020, 7:27 PM
nikas nikis
nikas nikis - avatar
4 Réponses
0
Here is one difference: public class Program { public static void main(String[] args) { A n1 = new A(); n1.aaa(); A n2 = new B(); n2.aaa(); } } public class A{ public void aaa(){ System.out.println ("aaa"); } } public class B extends A{ @Override public void aaa(){ System.out.println ("bbb"); } } // Output: // aaa // bbb
30th Oct 2020, 8:29 PM
Coding Cat
Coding Cat - avatar
0
So basically the difference is that if the super and subclass have the same method name, then it will prioritize in this case A n2 = new B(); the subclass method?
30th Oct 2020, 8:45 PM
nikas nikis
nikas nikis - avatar
0
In the first case A n = new A() U can only use propertys and methods of the Super Class. You dont have to create class B. It is useless. In the second case A n = new B() You're able to use overriden methods or propertys. But I also don't know so much of this. Have only this example above.
30th Oct 2020, 9:02 PM
Coding Cat
Coding Cat - avatar
0
Yes I was referring to this thanks
30th Oct 2020, 9:15 PM
nikas nikis
nikas nikis - avatar