search

Home  >  Q&A  >  body text

java中interface中定义方法,标准的调用方式

package com;

public interface ITest {

    public void test();
}

===========================================

package com;

public class Test1 implements ITest {

    @Override
    public void test() {
        // TODO Auto-generated method stub
        
        System.out.println("调用成功");
    }

}

======================================

package com;

public class Test2 {

    private static ITest iTest;
    public static void main(String[] args) {
        // TODO Auto-generated method stub
    
        iTest.test();
    }
    
    
    public ITest getiTest() {
        return iTest;
    }
    public void setiTest(ITest iTest) {
        this.iTest = iTest;
    }
    

}


为什么返回值为null???第一次用sf,求大神指点
大家讲道理大家讲道理2894 days ago413

reply all(4)I'll reply

  • 伊谢尔伦

    伊谢尔伦2017-04-18 09:22:52

    You just declared a variable named iTest and did not instantiate it. In JAVA language, you usually use the NEW keyword to instantiate an object.

    Change your code above to the following:

    package com;
    
    public class Test2 {
    
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            ITest tmp = new Test1();
            tmp.test();
        }
    }

    reply
    0
  • PHP中文网

    PHP中文网2017-04-18 09:22:52

    itest is a static variable, not initialized, is null, and its method cannot be called. Must be initialized first.

    reply
    0
  • ringa_lee

    ringa_lee2017-04-18 09:22:52

    Change it here to private static ITest iTest= new Test1()

    reply
    0
  • PHP中文网

    PHP中文网2017-04-18 09:22:52

    Because you don’t have new

    reply
    0
  • Cancelreply