📜 ⬆️ ⬇️

Class'y Class'y

Introductory


Probably, java-classes are the most famous part of it. We use them every day, write them, rule them. But there are many nuances that we do not even guess. And I love for this “our” java - it can always remain mysterious, mysterious. Today, some of its secrets will fall to your feet. Here you will find unusual code examples, a funny story and interesting statistics. Who cares, welcome under cat.

Few details


If you are a java-expert, code examples for you will be boring, and the rest, as always. At one time I was very interested in what is in java 7 outside and under the hood, how the class file format and so on is arranged. I had to get acquainted here with these documents . From there, I highlighted almost all the ideas for this article. Nevertheless, I apologize in advance for inaccuracies in terminology from fundamental theorists and experienced experts. I will not give answers to some questions because of their obviousness or an easy search for an answer.

And so the first question: "And what are the types and types of classes in java 7?" Most will answer correctly, but some will not. Very often forget to mention about local classes.

Local class


I did not quickly find a good definition of a local class in Russian, but there are problems with English, so in my own words: 'A local class is an internal and nested named class that is not a member of another class and is declared inside a code or method block' . A bit confusing? The example is simple:
')
Local class example
public class LocalClassExample { { //      class MyFirstLocalClass { int someField; }; } //   public void someMethod() { //   class MySecondLocalClass { }; } //    public static void someStaticMethod() { class MyThirdLocalClass { }; } //    public void someBlock() { try { } catch (Exception e) { class MyFourthLocalClass {}; } } } 

I looked through a lot of code in my life, but I never met any explicitly named class declarations inside a method. Maybe just not lucky. Have you met? But when I decided to collect statistics on the types and types of classes, I found out that local classes are present in rt.jar and moreover, they are used in such a well-known class like java.lang.Package. Live and learn. There is also an interesting statement: 'Anonymous class is a local class with no name' . For experts, the question: "Is this true?"

Annotation class


There are no people left who never wrote classes like annotations. And immediately a small example.

 @Target(ElementType.LOCAL_VARIABLE) @Retention(RetentionPolicy.RUNTIME) public @interface SmileAnn { String name() default ""; } 

But nevertheless, there is something to be surprised about. What do you think is the valid code below?

Strange annotation code
 @Target(ElementType.LOCAL_VARIABLE) @Retention(RetentionPolicy.RUNTIME) public @interface DontSmileAnn { String name() default ""; /**  ? */ static final String WHAT1 = "WHAT1"; /**  ? */ final String WHAT2 = "WHAT2"; /**     ? */ static class What3 { }; } 

In fact, nothing complicated. But let's continue, and how would you like such an example?

Heir
 public class ExtendsFromAnn implements DontSmileAnn { @Override public Class<ExtendsFromAnn> annotationType() { return ExtendsFromAnn.class; } @Override public String name() { return "ExtendsFromAnn"; } } 

The answers here are all simple - these are working code examples, because in fact, under the hood, the interface = interface, with a few reservations, so everything that can be written in the interface can also be in the annotations (again, with reservations). Inheritance in the code from the abstract type class I met in tests. I have everything about annotations, but there is a small example of an annotated type of array of strings and the form of its declaration:

Unusual shape
  public static void main(String[] args) { //   ,    . @SmileAnn String []simpleArray[] = {{}}; } 

I hope I did not tire you. But if this is not the case, then the next paragraph is for you.

Ordinary class


It is very difficult to surprise anyone with information about a regular class (excluding examples with generics). No matter how hard I tried, I couldn’t find anything meaningful. But I have one anecdote story.

Once the developer needed to write a utility class to solve the problem. It seems to have done everything correctly, wrote java-doc tests. Sent a patch for review.

 /**java-doc*/ public class Utils { /** ,     */ } 

The chief-Mikhalych looked at the patch and said - "Everything is OK, but let's make a foolproof - add a private constructor". As usual, the developer doesn’t want to redo the patch, but it’s impossible to top it up, therefore, overcoming yourself and, going over a certain line of subordination, the developer asked: "What do we have in the company, Mihalych, are you fools or do you specifically mean someone?" . But there is nothing to do, you need to redo it, and everything is simple - add a private constructor:

 /**java-doc*/ public class Utils { /**      */ private Utils() {} /** ,     */ } 

"Done" - shouted the developer, "Well done" - answered Mikhalych. He wanted to click submit, as the bell rang. At this very moment, the head of the department, freed from important matters, decided to shake old things and poked at the first patch for the review. 'Ltd!' - he squealed. 'Mikhalych, have you forgotten how to write the code? And where is the protection from deb * la? ' . The head of the department is a serious person, so Mikhalych says to himself: "What do we have in the company, deb * ly work, or do you mean someone specifically?" . Moody Mihalych wraps up a patch with a note to add abstract to the class. The bottom lip of the developer began to shake. So again?

 /**java-doc        */ public abstract class Utils { /**      */ private Utils() {} /** ,     */ } 

Ironically, on this day an intern came to the department and, having received his first assignment, he rushed into battle. His gaze settled on Utils , and his face showed both admiration and bewilderment. Grabbing courage, he loudly asked his first sparkling question: "Guys, how can you inherit from the class, with a private designer?"

Enumeration class


Who will surprise them now? Now, if 10 years ago. Therefore, here are some questions on how to understand the code. Do you think there is a difference in the declaration of the following elements of the listing and if so, why?

 public class EnumExample { public enum E1 { SIMPLE } public enum E2 { SIMPLE() } public enum E3 { SIMPLE { } } public enum E4 { SIMPLE() { } } } 

If you know the correct answer, the following question will seem easy to you: "What will be on the console?"

 public class EnumExample { public enum E1 { SIMPLE } public enum E2 { SIMPLE() } public enum E3 { SIMPLE { } } public enum E4 { SIMPLE() { } } public static void main(String[] args) { System.out.println(E1.SIMPLE.getClass().isEnum()); System.out.println(E2.SIMPLE.getClass().isEnum()); System.out.println(E3.SIMPLE.getClass().isEnum()); System.out.println(E4.SIMPLE.getClass().isEnum()); } } 

Of course, everything on the surface here is E3.SIMPLE and E4.SIMPLE are instances of the anonymous class of these enums. Therefore, the last 2 calls will give a false result. Be careful when using the enum class check with isEnum ().

Inner class


About internal classes of information a lot, how, what and what they eat. But many of whom I interviewed could not answer 2 questions. First, let's turn to an example:

Inner inner class
 //  InnerClassExample.java public class InnerClassExample { private int myField; public class InnerClass { private int myField; public class InnerInnerClass { private int myField; public InnerInnerClass() { } } } } //  InnerClassCreate.java public class InnerClassCreate { public static void main(String[] args) { } } 

And the first question: “How to access the myField field of the InnerClassExample class in the InnerInnerClass class constructor and is it possible?” Second question: 'How to create an instance of the class InnerInnerClass in the main method of the class InnerClassCreate?

Answer
 public class InnerClassExample { private int myField; public class InnerClass { private int myField; public class InnerInnerClass { private int myField; public InnerInnerClass() { int mf1 = InnerClassExample.this.myField; // : . //   : int mf2_0 = InnerClass.this.myField; int mf2_1 = InnerClassExample.InnerClass.this.myField; // ?  . int mf3_0 = InnerInnerClass.this.myField; int mf4_1 = InnerClassExample.InnerClass.InnerInnerClass.this.myField; // ?  . } } } } public class InnerClassCreate { public static void main(String[] args) { // 1. ,     ,    new   InnerInnerClass one = new InnerClassExample().new InnerClass().new InnerInnerClass(); // 2 InnerClass innerClass = new InnerClassExample().new InnerClass(); InnerInnerClass two = innerClass.new InnerInnerClass(); // 3 InnerInnerClass three = getInnerClass().new InnerInnerClass(); } private static final InnerClass getInnerClass() { return new InnerClassExample().new InnerClass(); } } 

With code examples, perhaps that's all.

Class statistics


I collected statistics on some types and types of classes in rt.jar from jdk1.7.0_60 under Mac Os. And such data
Class descriptionamount
Local21
Annotations137
Transfers278
Internal (non static)1482
Abstraction1560
Anonymous2230
Interfaces2352
Nested static3222
Ordinary12943
In total, 1998 classes fell under my analysis. Thank you for your attention and pleasant pastime.

Source: https://habr.com/ru/post/321024/


All Articles