Java static class compile

Can we declare a class Static in Java? Top Level and Nested static class Example

The answer to this question is both Yes and No, depending on whether you are talking about a top-level class or a nested class in Java. You cannot make a top-level class static in Java, the compiler will not allow it, but you can make a nested class static in Java. A top-level class is a class that is not inside another class. It may or may not be public like you can have more than one class in a Java source file and only needs to be public , whose name must be the same as the name of the file, rest of the class or interface on that file may or may not be public. On the other hand, a nested class is a class inside a top-level class. It is also known as the inner class or member class in Java.

Now, let’s think about what is the meaning of static class, why would someone want to make a class static in Java? If you are familiar with the concept of a static method and static variable in Java, then you know that anything static can be accessed without creating an instance of the class.

For example, you can access the static variable directly as ClassName.variable and you can invoke the static method as ClassName.staticMethod() , this is a great convenience for calling utility method or accessing constants.

This convenience is the main reason Java programmers like to declare a nested class as static in Java. Remember, A nested class, if it’s not static then you can’t create its instance without first creating an instance of the outer class, which is a bit inconvenient. Such classes are known as the Inner class and they are always associated with an instance of the outer class.

Btw, if you are new to the world of object-oriented programming and design then I also suggest these Software Architecture and Design courses. It’s a great resource to understand the complete process of object-oriented analysis and design for creating quality software.

Nested Static Class in Java

A nested class is actually a member of a top-level class, so it’s not much different from a static variable. All instances of the top-level class will have a reference of the same nested class if it’s static , otherwise, each of them will refer to a different instance of the nested class.

One of the main advantages of making a nested class static is how you instantiate it. Suppose you declare a nested class B inside a top-level class A, then it would be referred to as A.B and you can create an instance of this class as A.B nestedStaticInstance = new A.B() , unlike Testing.B bs = new Testing(). new B(); for creating an instance of a non-static class, also known as an inner class.

Читайте также:  Form

So, Yes, you can declare a class static in Java, provided the class is inside a top-level class. Such clauses are also known as nested classes and they can be declared static, but if you are thinking to make a top-level class static in Java, then it’s not allowed. If you do so, the compiler will complain saying «illegal modifier for the class, only public, abstract and final are permitted».

Now, let’s see some code in action to prove our point. First, let’s try to declare a top-level class static in Java and see if we can do it or no.

How to make a static class in Java

You can see the compile-time error, which means it is illegal to use the static modifier with a top-level class in Java. It doesn’t matter whether the class is public or package and whether its name is the same as the name of the Java source file. In short, you cannot make a top-level class static in Java i.e. the class which is not inside another class. Here is another example, where I have tried to make a non-public but top-level class static in Java:

Can you make a class static in Java

You can see, still, the same compile-time error, «illegal modifier for the class, only public, abstract and final are permitted» is thrown». If you are hearing about nested or inner class first time, You should first read a good core Java book like Head First Java to learn more about nested class in Java.

what is static class in Java

Now, let’s try to make a nested class i.e. a class inside the top-level class static in Java. As per the theory, you can declare a nested class static in Java, let’s see that in code.

This time there is no compiler error, it means you can make a nested class static in Java. I have also shown you how you can create an instance of the nested static class in Java. You can see, you can create an instance without creating an instance of the outer class which was not possible with a non-static nested class or inner class.

Can we declare a class Static in Java?

That’s all about whether you can declare a class static in Java or not. Of course, you cannot make a top-level class static in Java but you can always make a nested class static in Java. In fact, it is one of the best practices and also suggested in Effective Java to prefer the nested static class instead of the non-static inner class.

  • Can you overload or override the static method in Java? (answer)
  • Can you override a private method in Java? (answer)
  • Can you run a Java program without the main() method? (answer)
  • Can you make an array volatile in Java? (answer)
  • Can you overload or override the main method in Java? (answer)
  • Can an Abstract class have a constructor in Java? (answer)
  • Java Programming Interview Exposed by Markham (book)

Источник

How to Compile a Class at Runtime with Java 8 and 9

In some cases, it’s really useful to be able to compile a class at runtime using the java.compiler module. You can e.g. load a Java source file from the database, compile it on the fly, and execute its code as if it were part of your application. In the upcoming jOOR 0.9.8, this will be made possible through https://github.com/jOOQ/jOOR/issues/51. As always with jOOR (and our other projects), we’re wrapping existing JDK API, simplifying the little details that you often don’t want to worry about. Using jOOR API, you can now write:

// Run this code from within the com.example package Supplier supplier = Reflect.compile( "com.example.CompileTest", "package com.example;\n" + "class CompileTest\n" + "implements java.util.function.Supplier \n" + ">\n" ).create().get(); System.out.println(supplier.get());
Supplier supplier = Reflect.compile( `org.joor.test.CompileTest`, `package org.joor.test; class CompileTest implements java.util.function.Supplier  < public String get() < return "Hello World!" >>` ).create().get(); System.out.println(supplier.get());

What happens behind the scenes?

Again, as in our previous blog post, we need to ship two different versions of our code. One that works in Java 8 (where reflecting and accessing JDK internal API was possible), and one that works in Java 9+ (where this is forbidden). The full annotated API is here:

package org.joor; import java.io.ByteArrayOutputStream; import java.io.OutputStream; import java.lang.invoke.MethodHandles; import java.lang.invoke.MethodHandles.Lookup; import java.net.URI; import java.util.ArrayList; import java.util.List; import javax.tools.*; import static java.lang.StackWalker.Option.RETAIN_CLASS_REFERENCE; class Compile < static Classcompile0( String className, String content, Lookup lookup) throws Exception < JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); ClassFileManager manager = new ClassFileManager( compiler.getStandardFileManager(null, null, null)); Listfiles = new ArrayList<>(); files.add(new CharSequenceJavaFileObject( className, content)); compiler.getTask(null, manager, null, null, null, files) .call(); Class caller = StackWalker .getInstance(RETAIN_CLASS_REFERENCE) .walk(s -> s .skip(2) .findFirst() .get() .getDeclaringClass()); // If the compiled class is in the same package as the // caller class, then we can use the private-access // Lookup of the caller class if (className.startsWith(caller.getPackageName() )) < result = MethodHandles .privateLookupIn(caller, lookup) .defineClass(fileManager.o.getBytes()); >// Otherwise, use an arbitrary class loader. This // approach doesn't allow for loading private-access // interfaces in the compiled class's type hierarchy else < result = new ClassLoader() < @Override protected ClassfindClass(String name) throws ClassNotFoundException < byte[] b = fileManager.o.getBytes(); int len = b.length; return defineClass(className, b, 0, len); >>.loadClass(className); > > return result; > // These are some utility classes needed for the JavaCompiler // ---------------------------------------------------------- static final class JavaFileObject extends SimpleJavaFileObject < final ByteArrayOutputStream os = new ByteArrayOutputStream(); JavaFileObject(String name, JavaFileObject.Kind kind) < super(URI.create( "string:///" + name.replace('.', '/') + kind.extension), kind); >byte[] getBytes() < return os.toByteArray(); >@Override public OutputStream openOutputStream() < return os; >> static final class ClassFileManager extends ForwardingJavaFileManager  < JavaFileObject o; ClassFileManager(StandardJavaFileManager m) < super(m); >@Override public JavaFileObject getJavaFileForOutput( JavaFileManager.Location location, String className, JavaFileObject.Kind kind, FileObject sibling ) < return o = new JavaFileObject(className, kind); >> static final class CharSequenceJavaFileObject extends SimpleJavaFileObject < final CharSequence content; public CharSequenceJavaFileObject( String className, CharSequence content ) < super(URI.create( "string:///" + className.replace('.', '/') + JavaFileObject.Kind.SOURCE.extension), JavaFileObject.Kind.SOURCE); this.content = content; >@Override public CharSequence getCharContent( boolean ignoreEncodingErrors ) < return content; >> >
  • Find the caller class of our method
  • Get a private method handle lookup for that class if the class being compiled is in the same package as the class calling the compilation
  • Otherwise, use an arbitrary class loader to define the class

Источник

Details of dynamic and static compilation instances in Java

3. In terms of language nature, java is a high-level programming language with strict requirements on variable checking, while javascript is a simple interpreted scripting language with weak requirements on variable checking.

javascript is a dynamic language, while java is «semi-dynamic».

javascript is dynamic, not to be doubted. Why is java semi-dynamic? See the following code:

The Frame class calls its methods by directly using new1 Color objects, which are identified at compile time to determine the relationship. I think this is a manifestation of the static nature of the java language. If the compiled Color. class file is missing, an error is reported.

We find java dynamic if we follow the following code:

 public class ColorImp implements Color < public void changeColor()< System.out.println(" Change the color to red "); >> 

Note the Frame class. When we compile it, only two class files will show up — Frame.class and Color.class. Then we run the program and throw an exception — java.lang.ClassNotFoundException — because we didn’t compile ColorImp.

So, we open another cmd process, compile the ColorImp class separately, and then type ColorImp into the previous cmd dialog. The program will run normally.

This allows us to dynamically load a class without stopping the program. I think this shows the dynamic nature of Java. From the above example, I consider java to be a «semi-dynamic» language.

As you can see, the example above USES the Color interface class. I have to mention a little touch of interface here.

When using a database, the Java language just defines one database interface and then different databases to implement this excuse. These include (take the mysql database for example)
Load database driver:

 Class.forName("com.mysql.jdbc.Driver"); 

Establish a link to the database:

 java.sql.Connection conn = java.sql.DriverManager.getConnection( url, user, password); 

Get the compiled object, result set object, etc., which just define the interface, and leave the implementation to the database developer, as long as the interface is implemented. This reflects the extensibility and standardization of the interface.

Thank you for reading, I hope to help you, thank you for your support to this site!

Источник

Оцените статью