In what order do local and anonymous classes compile in java? - java

Assume that I have two local classes with the same names, but they're defined in different methods. In what order will they compile and what names are they going to have?
class ExampleClass {
public void test() {
NestedClass.nestedTest2();
NestedClass.nestedTest();
}
private static class NestedClass {
private static int a;
public static void nestedTest() {
class Test1 {
void method1() {}
}
}
public static void nestedTest2() {
class Test1 {
void method2() {}
}
}
}
}
Using javac command I get these compiled files
ExampleClass$NestedClass$1Test1
ExampleClass$NestedClass$2Test1
There are other files, I just don't really thing it's necessary to list them all.
The question is, how come the first file (ending with $1Test1, which is defined in nestedTest() method ) get compiled earlier than the other one (defined in method nestedTest2)? What does the order depend on? As you see I also tried to call test methods in ExampleClass to change the order, but I didn't believe it would help and it actually doesn't.

Related

How can I make classes implement an interface and print their methods based on a given parameter in Java?

I think this might be a very basic Java question, and I apologize since I'm a beginner, but I want to understand what am I getting wrong here: I'm supposed to create a package, and inside it, I must create the following:
an interface with a method (the question says nothing besides it, so I created it empty)
2 classes, A and B, which must implement the method created in said interface and print their own names
A third class, C, which must override B's implementation
And an Execute method inside the main class. This method must receive a letter as a parameter, no matter if it's capital case or not, and execute the method of the corresponding class (i.e. if this method receives as a parameter the letter A, it must execute the method belonging to class A)
So far I came up this this, but the code receives the input, and doesn't do anything:
Interface
public interface Test {
public static void testInterface() {
}
}
Classes
public class Teste {
public static void main(String[] args) {
class A implements Test {
public void testInterface() {
System.out.println("A");
}
}
class B implements Test {
public void testInterface() {
System.out.println("B");
}
}
class C extends B {
public void testInterface() {
System.out.println("C");
}
}
Scanner inputLetter = new Scanner(System.in); // Create a Scanner object
System.out.println("Enter a letter from A to C: ");
String resLetter = inputLetter.nextLine(); // Read user input
if (resLetter == "A") {
A a = new A();
a.testInterface();
}
if (resLetra == "B") {
B b = new B();
b.testInterface();
}
if (resLetra == "C") {
C c = new C();
c.testInterface();
}
}
}
To be quite honest, I may be messing up with the code's structure too, since I'm not too sure of how should I organize it - I didn't create the Execute method because I had a lot of trouble creating classes without the main method, and couldn't put a method inside another, and I want to make it as simple as possible to make it work before I can try bolder things, so any help will be of great value!
You're on a good way. I'll just post some information to get you over your current roadblock.
public interface MyTestInterface {
void testInterface();
}
Interfaces will just "announce" a method. This just tells you (and the compiler) that any Class that implements MyTestInterface has to supply a method called testInterface(). Don't make them static, as this would prevent any class implementing the interface from overriding the method.
Put your classes in their own .java file. While you can define a class within a class (so called Inner Class), it has some implications.
A.java
public class A implements MyTestInterface {
#Override
public void testInterface() {
// Objects of Class A do something here
}
}
MyMain.java
public class MyMain {
public static void main(String[] args) {
MyTestInterface implementedByA = new A();
implementedByA.testInterface();
}
}
Since it implements MyTestInterface, an Object of Class A is both an instance of A and an instance of MyTestInterface. This allows you, to declare a variable of type MyTestInterface and assign it an implementation of one implementing class.
And as #Amongalen mentioned: How do I compare strings in Java?

How do you transfer a variable defined in the main method of one class to another?

I have seen this done in many programs but I cant seem to follow the programming logic.
Lets say you have a simple class, ClassB. And in ClassB's main method you define an integer variable:
public class B {
public static void main(String[] args) {
int stuff = 333;
}
}
How can you transfer the variable to a different class, say ClassA, to be used.
public class A {
public static void main(String[] args) {
System.out.println(stuff);
}
}
Can someone please explain this to me in simple terms. I've been trying to learn this for 2 hours and cant wrap my head around it.
public static void main(String[] args) is meant to be used as a starting point for a Java program. Probably it's better to rename one of your methods to something else.
The problem you are seeing, is that the scope of the variable int stuff is limited to the main() method of class B, because it is declared within the body of the main() method. In order to make it visible, you need to declare it as a public field (which can be static in your case).
I propose you change your program like follows:
public class A {
public static int stuff;
public static void initStaticMembers() {
stuff = 333;
}
}
public class B {
public static void main(String[] args) {
A.initStaticMembers();
System.out.println(A.stuff);
}
}
I renamed the main() method of A to initStaticMembers() and dropped the method parameters, since they are not needed in our case. In order to use the field A.stuff in B, the method A.initStaticMembers() needs to be called first.
Of course there are ways to improve this program, but I think you should learn Java one step at a time.
You shouldn't have 2 main methods. Only one class should (typically):
ClassA.java
public class A {
public static void main(String[] args) {
ClassB b = new ClassB();
System.out.println(b.stuff);
}
}
ClassB.java
public class B {
public int stuff = 333; // member variable
}
You instantiate the second class in the first one, then you're granted access to its public member variables.

Program will give an error if method not marked public ( all classes are in the same file)

I am trying to create an Anonymous class during which I came across following problem. In the following code when I change display method access modifier to default it gives an error but when I change it to public it works fine. Could you explain it to me why this happens.AFAIK public and default are work in similar as long as all classes are in same package. Please correct me if I am wrong.
//from file : Skg.java
package sandeep2;
class Skg1
{
public void display()
{
System.out.println("sandeep here");
}
}
class Skg2 {
public void say()
{
System.out.println("Skg2");
}
Skg1 obj = new Skg1()
{
**public void display()** //wont work if this is not public ????????????
{
System.out.println("I am ANONymous");
}
};
}
public class Skg {
public static void main(String[] args)
{
Skg2 x = new Skg2();
x.obj.display();
}
}
Class Skg2 attempts to create an instance of an anonymous inner class as a subclass of class Skg1. That anonymous inner class overrides Skg1.display(), which is public. You cannot override a method to reduce its visibility. Java does not permit it, and it would violate the substitution principle if you could do it.

Why doesn't the class containing main have to be public?

I declared the following class
class A { //not public
public static void main(String args[]) {
System.out.println("done");
}
When I compile and run it, it runs fine and prints the output "done". Same behavior even when I declare it as being in a "package a;"
However, if JVM spec mandates that main method should be public since "it can't see main otherwise", shouldn't it apply to the class as well?
If the JVM "can't see" A.main() when it is not declared public, how is it able to see the class A itself.
Is there any explanation for this other than "because the specification says so"?
The JVM has access to every class in the application all the time because one of its responsibilities is enforcing visibility rules. Therefore, one can draw the conclusion that it can ignore visibility rules if need be (e.g. when the user starts the application, the JVM has to find the entry point, which is main()).
In other words, the JVM is not a class accessing this function, so visibility doesn't apply. It is basically the overseer, managing the application from execution to termination.
For reference, see Execution.
When you declare a class private, you're not making it "invisible", and the same goes for your methods. Declaring a method private simply means it's not callable from outside your class. A static public method of a private class is publicly callable.
The reason the JVM can see a non-public class is because it controls visibility, meaning it sees everything and decides what can see/call/access what.
The use of public on a class is different than on a method, but the concept is the same.
On a method, the public keyword means the method can be used outside the class. An example would be:
class A {
public static void do() {
// Do something
}
}
class B {
public static void main(String[] args) {
A.do(); // This works because do() is public and static
}
}
The same concept applies to classes, but in a different way.
Using public on a class means that it can be used outside the current .java file (it will have its own .class file).
Here's an example:
//C.java
class C {
static void do() {
// Do something
}
public static void run() {
A.do(); // Works because A.do() is public and static
B.do(); // Does not work because B is not a public class
}
}
//A.java
public class A {
public static void main(String[] args) {
B.do(); // Works because B is in the same file
do(); // Duh...
}
public static void do() {
// Do something
}
}
class B {
static void do() {
// Do something
}
}

Java local class .class file names

What will be the name of the .class file when local classes with same name are present in more than one instance method of same class? How can JVM differentiate these local classes?
Code:
public class Test {
public static void main(String[] args) {
}
public void method1() {
class class1 {
}
}
public void method2() {
class class1 {
}
}
}
Generated classes:
Test.class
Test$1class1.class
Test$2class1.class
So it's OuterClass$(number)InnerClass
With both local classes and anonymous classes the compiler adds a number to the generated name.
Compiling the below code produced classes Test.class, Test$1Local.class, Test$2Local.class and Test$1Another.class so the compiler (jdk1.6.0_24) always adds a number to the name (maybe to avoid conflicts with inner classes) and if there are two local classes with the same name then it increments the number to avoid conflicts.
public class Test {
public void foo() {
class Local {
}
}
public void bar() {
class Local {
}
}
public void baz() {
class Another {
}
}
}
Consider the following class:
public class test
{
private void meth1()
{
class abc{}
}
private void meth2()
{
class abc{}
}
}
It will generate the following class files:
test.class
test$1abc.class
test$2abc.class
The JVM uses the format org.package.OuterClass$InnerClass
Anonymous classes are assigned a unique number.
http://www.retrologic.com/innerclasses.doc7.html
The format of the output .class file's name is PublicOuterClass$InnerClass.class. If the inner class is an anonymous class, then it will be replaced with a number and sequentially numbered starting with 1.

Categories

Resources