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

Popular posts from this blog

Spring Boot + JPA + Hibernate: Unable to locate persister -

go - Golang: panic: runtime error: invalid memory address or nil pointer dereference using bufio.Scanner -

c - double free or corruption (fasttop) -