Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
161 views
in Technique[技术] by (71.8m points)

java - What is the use of creating a class inside interface and interface inside class

I want to know what is the need of placing a class inside interface and an interface inside class?

class A {
   interface B {}
}

interface D {
   class E {}
} 
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This i am copying and pasting from some link (i earlier did and sharing with you) May be that can help you a bit.

1)

interface employee{
class Role{
      public String rolename;
      public int roleId;
 }
Role getRole();
// other methods
 }

In the above interface you are binding the Role type strongly to the employee interface(employee.Role). 2) With a static class inside an interface you have the possibility to shorten a common programming fragment: Checking if an object is an instance of an interface, and if so calling a method of this interface. Look at this example:

  public interface Printable {
    void print();

    public static class Caller {
        public static void print(Object mightBePrintable) {
                if (mightBePrintable instanceof Printable) {
                        ((Printable) mightBePrintable).print();
                }
        }
    }
}

Now instead of doing this:

  void genericPrintMethod(Object obj) {
    if (obj instanceof Printable) {
        ((Printable) obj).print();
    }
}

You can write:

   void genericPrintMethod(Object obj) {
         Printable.Caller.print(obj);
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...