inheritance - Can interface in java access to base class variable? -
when create interface reference variable base class type object. possible access variable in it's base class ?
how can "bmw" defined in car constructor ?
without creating method in interface must implemented in base class return variable.
string getname(); , in base class public string getname(){return name;}
interface drive(){ void start(); } public class car implements drive{ string name; car(string n){ this.name=n; } public void start(){ } } public static void main(string [] args){ drive d = new car("bmw"); string nameofthecar = d.name; //not work string nameofthecar = ((car)d.name); //not work
you have 2 way it.
make interface aware of property (implementing in class), eg.:
public interface drive { string getname(); }
otherwise have cast interface object type contains property you, did it, wrong syntax:
string nameofthecar = ((car)d.name); //not work
instead of:
string nameofthecar = ((car) d).name; //not work
Comments
Post a Comment