最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

java - How is it possible to access Object class methods using an interface reference variable? What is the underlying mechanism

programmeradmin3浏览0评论

I am working on a Java project and I have defined an interface, a class that implements this interface, and a user class to test the implementation. I am confused about how I can call methods from the Object class using an interface reference variable.

ATM INTERFACE

package interfaceconcept;

public interface ATM {
    void withdraw();
    void checkBalance();
    void pinGenerate();
}

CONCRETE IMPLEMENTING SUB-CLASS

package interfaceconcept;

package interfaceconcept;

public class Bank {
    private class SBI implements ATM {
        public void withdraw() {
            System.out.println("Amount withdrawn successfully!!");
        }

        public void checkBalance() {
            System.out.println("Balance available!!");
        }

        public void pinGenerate() {
            System.out.println("PIN generated!!");
        }
    }

    public ATM atm() {
        return new SBI();
    }
}

USER LOGIC CLASS

package interfaceconcept;

public class User {
    public static void main(String[] args) {
        Bank bank = new Bank();
        ATM atm = bank.atm();
        atm.checkBalance();
        atm.withdraw();
        atm.pinGenerate();

        // Accessing Object class methods through atm reference
        System.out.println(atm.toString());   /*How can we access Object class methods through ATM interface reference variable? */
        System.out.println(atm.equals(atm));  /* How can we access Object class methods through ATM interface reference variable? */
    }
}

Doubt Basically, whenever we create an interface in java it does not inherit any methods from the Object class but when we create an abstract class it inherits the 11 non static methods from Object class this nature is not shown by an interface. So that's why we use an interface to achieve 100% abstraction Now, I'm unable to understand how come we are accessing the Object class members with the upcasted reference variable of ATM class because the compiler will check the syntax and semantics first and according to that we can access only super class and super most class members with the help of upcasted reference variable but in this case the interface does not inherit the 11 non static methods how come we can access methods of Object class I might be wrong somewhere in understanding the concept but I have explained whatever I have known please provide me the detailed answer so that I can have a better understanding Thanks in Advance.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论