• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Applet

 
Raj Thaker
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi !
The following code defines a simple applet:
import java.applet.Applet;
import java.awt.*;
public class Sample extends Applet {
private String text = "Hello World";
public void init() {
add(new Label(text));
}
public Sample (String string) {
text = string;
}
}

It is accessed form the following HTML page:
<html>
<title>Sample Applet</title>
<body>
<applet code="Sample.class" width=200 height=200></applet>
</body>
</html>
What is the result of compiling and running this applet:
A. Prints "Hello World".
B. Generates a runtime error.
C. Does nothing.
D. Generates a compile time error.
Select the most appropriate answer.
Ans : B
Please can you explain me the answer?

Thanks
--------------------------------------------------------
Examine the following code which includes an inner class:

public final class Test4 implements A {
class Inner {
void test() {
if (Test4.this.flag); {
sample();
}
}
}
private boolean flag = false;
public void sample() {
System.out.println("Sample");
}
public Test4() {
(new Inner()).test();
}
public static void main(String args []) {
new Test4();
}
}

What is the result:
A. Prints out "Sample"
B. Program produces no output but terminates correctly.
C. Program does not terminate.
D. The program will not compile
Select the most appropriate answer.
Ans : A
Please explain me the answer.
Thanks.


 
Frank Carver
Sheriff
Posts: 6920
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This isn't really a servlet question, so I've moved it to the Applets forum.
 
Stephanie Grasson
Ranch Hand
Posts: 347
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Raj!
In answer to your applet question, the answer given, B, is correct. The code will generate a runtime error for this reason:
In Java, if no constructors are defined for a class, the compiler creates a default constructor that takes no arguments. If the programmer has defined any constructors for their class, the compiler will not generate this default constructor.
In the code you posted, a constructor is defined which takes one argument:

Therefore, the no-argument default constructor is not generated by the compiler.
The code will compile fine, because all syntax is correct. However, if you try to run the code, the result is:
Applet exception: error: java.lang.NoSuchMethodError
because no default constructor was found.
I hope this clears up your question, but if you need more info let us know.
Stephanie
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic