If your solution to the previous exercise is something like what is given below, you are perfectly on track.
1. Our receptionist object needs to greet us when we meet it. In simple terms any verb in a sentence translates to a method or a step in a method. So our Receptionist class should have a meet method which does the job of greeting.
2. We create an instance of this class and name it say receptionist
3. We invoke the meet method in the receptionist object to greet us.
Here is the actual code that does what we want.
public class Receptionist{
void meet( ){
greetVisitor( );
}
void greetVisitor( ){
System.out.println(“Hello Guest! Welcome!”);
}
public static void main(String args[]){
Receptionist receptionist = new Receptionist( );
receptionist.meet( );
}
}
Great… now how to run this?
1. Save this in a file name Receptionist.java.
2. Compile the code using javac Receptionist.java
3. Run the program using java Receptionist
Your output should ideally be - Hello Guest! Welcome!
Not sure how to do the compilation or problems in compiling? Checkout http://java.sun.com/docs/books/tutorial/getStarted/cupojava/win32.html for setting up the execution environment.
If you take a closer look at this program, there are a lot too many questions to ask. Let me list down whatever I see as a first time Java programmer. You can add questions if you have any.
1. What does void stand for?
2. What happens in System.out.println?!
3. What is this main( ) method? Does it have any significance?
4. why is it termed public static void main( ) while other methods are termed just void functionName( )
5. Am I reading the code correctly? Are we creating an object of Receptionist inside a method in Receptionist? How is this possible?
6. Can I have any name for my variables? Wont the receptionist object be confused with Receptionist class by the compiler?
7. Why is there a limitation on the file name?
8. Should I always mark my class public? What does it mean?
9. If I have the greeting line in greetVisitor( ) method why should I have another method meet( ) where we call the greetVisitor( ) method?
For now, I leave it to you to answer these questions. Don’t skip these questions. Even if you can’t answer them, at least guess before you continue reading.
Monday, March 12, 2007
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment