Java access constants defined in interfaces

Source: Internet
Author: User

When we define constants, we can define constants in the interface, such as:

package org.zy.demo.base;
public interface InterfaceDemo {
  final String name="this is my name";

}

The above are the interfaces and constants that I define.

The definition of a constant does not indicate a public static

I implement this interface:

package org.zy.demo.base;
public class InterfaceImpl implements InterfaceDemo{

}

So how do we access it?

I made a demo:

package org.zy.demo.base;
public class MainDemo {
  public static void main(String[] args){
    InterfaceImpl ii=new InterfaceImpl();
    String name = InterfaceDemo.name;
    System.out.println(name);
    String n=ii.name;
    System.out.println(n);
  }
}

The results of the implementation are as follows:

This are my name

This are my name

In the above program, we used two different methods to get the value of name.

From the first method we can know:

In fact, all the properties and methods defined within the interface are of public type. If it is a property, the default is public static

The second method allows us to know that this property is public. How else would we be able to access it directly?

From the above conclusion we can see why we define the methods in the interface without adding public, such as mud can define the following methods:

Public Interface A{
  A();
}

Of course you can also:

Public Interface A{
  Public A();
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.