+ 1

Why output 90

class bike{ int speedlimit=90; } class car extends bike{ int speedlimit=160; } class main{ public static void main(String [] args){ bike b=new car(); System.out.println(b.speedlimit); } }

18th Mar 2020, 6:01 PM
Slaugther
Slaugther - avatar
3 odpowiedzi
0
Polymorphism allow you to call method of object being referred despite the type of reference which is referring to it.(Reference can be of type baseclass) That being said, Polymorphism is applicable to methods, not the data members. If you modify your code as follows, you'll see how the method of subclass is being called through reference of type baseclass: class bike{ int getSpeedLimit(){ return 90; } } class car extends bike{ int getSpeedLimit(){ return 160; } } class Main{ public static void main(String [] args){ bike b=new car(); System.out.println(b.getSpeedLimit()); } }
18th Mar 2020, 6:28 PM
🇮🇳Omkar🕉
🇮🇳Omkar🕉 - avatar
0
b is reference variable of parent class bike. First it search for the variable in original reference type. If there is no such variable it will search in child class. If you want car class variable, through parent reference, remove variable in parent. Or call through child class reference...
18th Mar 2020, 6:18 PM
Jayakrishna 🇮🇳
0
Thx
18th Mar 2020, 6:29 PM
Slaugther
Slaugther - avatar