Trisha
Trisha

Reputation: 51

Access class variable using Interface type

I've following class

class MyClass implements Intrfc {

String pickmeUp = "Its Me";

public static void main(String[] args){

Intrfc ob = new MyClass();
ob.pickmeUp;  ---> How can I access this way ?

  }

}

Is there any way to access class variable using Interface type ?

Upvotes: 1

Views: 7432

Answers (4)

Mohd Yusuf
Mohd Yusuf

Reputation: 21

If you want to use the method of a class using the object of an interface you can do it as follows:

//Interface:
public interface TestOne {  
    int a = 5;
    void test();    
    static void testOne(){      
        System.out.println("Great!!!");

    }

    default void testTwo(){

        System.out.println("Wow!!!");

    }
}
//-------------------
//Class implementing it:
package SP;
public class TestInterfacesImp implements Test1, TestOne{   
    @Override
    public void test() {
        System.out.println("I Love java");      
    }

        public void testM() {
            System.out.println("I Love java too");
        }

    public static void main(String[] args) {
        TestOne.testOne();      
        TestOne obj = new TestInterfacesImp();
        obj.testTwo();
        TestInterfacesImp objImp = new TestInterfacesImp();
        objImp.test();
        ((TestInterfacesImp) obj).testM(); //Here casting is done we have casted to class type


    }
}

Hope this helps...

Upvotes: 2

GhostCat
GhostCat

Reputation: 140457

Is there any way to access class variable using Interface type ?

No. That is the whole point of an interface.

And yes, interfaces only give you behavior (methods), not "state" (variables/fields). That is how things are in Java.

Of course, you can always use instanceof to check if the actual object is of some more specific type, to then cast to that type. But as said, that defeats the purpose of using interfaces!

Upvotes: 5

Michal Horvath
Michal Horvath

Reputation: 183

No, you can't access the class variable using interface type, but the interface can define method that can access to the variable.

interface Intrfc {

    public String getPickmeUp();

}


class MyClass implements Intrfc {

    String pickmeUp = "Its Me";

    public String getPickmeUp(){
        return pickmeUp;
    }

    public static void main(String[] args){

        Intrfc ob = new MyClass();
        ob.getPickmeUp();

    }

}

Upvotes: 4

Andronicus
Andronicus

Reputation: 26046

In this definition:

class MyClass implements Intrfc {
    String pickmeUp = "Its Me";
}

the field pickmeUp is not even a member of Intrfc interface, so there is no possibility to reach for it using just the interface. pickmeUp is a member of a concrete class - MyClass.

Upvotes: 2

Related Questions