Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Thread

 
neelam samnani
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In one of the test paper i read this question, and unable to understand it , whether comlier will print the statement "Before start method" or not . 'coz when i m compling this code i m getting complirt error.?
Pls. suggest me right answer.

1: public class Q1 extends Thread
2: {
3: public void run()
4: {
5: System.out.println("Before start method");
6: this.stop();
7: System.out.println("After stop method");
8: }
9:
10: public static void main(String[] args)
11: {
12: Q1 a = new Q1();
13: a.start();
14: }
15: }
 
Jane Griscti
Ranch Hand
Posts: 3141
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Neelam,
Are you seeing the following error?

The code compiles ok; the above is just a warning because stop() is deprecated.
You can still run the program and see the result.

------------------
Jane Griscti
Sun Certified Programmer for the Java� 2 Platform
 
Amit Madan
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi
your code is incorrect it will give error that you can't call non-static method from a static method.use following code you will get whatever you want.
public class Q1 extends Thread{
public Q1(){
start(); //start should be use like that
}
public void run(){
System.out.println("Before");
this.stop();
System.out.println("After");
}
public static void main(String arg[]){
Q1 a=new Q1();
}
}
Amit Madan
 
Jane Griscti
Ranch Hand
Posts: 3141
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Amit,
The original code does not have an error. You can compile and run it. The output is "Before start method".
The compiler does give you a warning about the deprecated stop() method but warnings do not stop a .class file from being created.
You don't get an error about calling a non-static method from a static method. 'a.start()' is calling the start() method on the instance 'a'. If you try to call start() without first creating an instance, then you'll get an error about a static method calling a non-static method.

Hope that helps.
------------------
Jane Griscti
Sun Certified Programmer for the Java� 2 Platform
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic