Re: 2 newbie questions

From: Steve (snd2ss_at_yahoo.com)
Date: 02/21/05


Date: Mon, 21 Feb 2005 08:57:45 GMT

Have you recieved an answer to your question yet?
If so, then kewl!
If not, then feel free to retrieve what you can from my answer which
follows.

"Rodrigo Milhaven" <swampyfern@hotmail.com> wrote in message
news:WyqQd.12428$4I5.491273@news20.bellglobal.com...
> I've been taking a Java course for the past month, so I'm relatively new
> to the whole thing. I've got no problems writing code in C, BASIC, Cobol
> and scripting in a couple of UNIX shells, so the process isn't alien to
> me. What's got me baffled is this whole object oriented thing. Up until
> now, all the programs we've written have been single-class procedural
> jobs, similar to what you'd do in C, a couple of functions thrown in, but
> nothing overly complicated.
>
> Now...
>
> I need to write a program that consists of three classes. Or are they
> objects? One that calculates the volume of a sphere, one that calculates
> the volume of a fish tank and a third that ties everything together. So I
> wrote the thing in C in 2 minutes, in non-OO Java in about 3 minutes, just
> to get the mechanics right. Now I'm stuck.
>
> If someone could just explain to me how objects communicate with one
> another, and how you call functions from a completely different file,
> that'd be great. The instructor never really explained it very well, most
> of the class is baffled by the sheer concept and the text is nearly
> useless on the matter.
>
> That's my first problem.
>
> Second... What the heck is Java's equivalent to scanf() in C or cin in
> C++?
>
> Have a good day.
>

The short version:

You create a .java file. This is the simplest form:

class FileName{

    public static void main(String [ ] arg){
        // do stuff like:
       System.out.println("I am speaking here.");
    } // end method: main
} // end class

Then you do the standard stuff.
You ask the compiler to do its thing with: javac FileName.java
which creates a file named: FileName.class
and then run the program with: java FileName (and it implies .class)

...but this is merely running java like a procedural language, which you
could do.

Then you modify this by asking it to create a constructor method and calling
it from the main method.

public class FileName{

  public FileName(){
        // do stuff
       System.out.println("Now you're talking to me.");
  }// end constructor
   public static void main(String[ ] arg){
      FileName fn = new FileName(); // this asks the compiler to create an
instance of the constructor
   } // end method: main
} // end class

Then, you make another text file and save it as a Tank.java file.

public class Tank{

   public Tank(){
        System.out.println("I am a tank."); // not very much like what a
tank would do, but ... wait
    }// end constructor of this class which makes it an object
// notice that you aren't using the public static void main stuff here
cause you can only ask the runtime machine to run one main method (that's
why that's static)
}// end class

Then, you include a request to make one of these tanks in your SomeFile
program:

public class FileName{

   private Tank t; // here you declare to the compiler that you will make
a tank.

   public FileName(){ // being the constructor

     t = new Tank(); // that is a call to the compiler to make room in
memory and go to the constructor of the tank to make an instance of itself
   }// end constructor

   public static void main(String [ ] arg){
      FileName fn = new FileName();
   } // end constructor

} // end class

That ties things together, with a reference to the other files, tank and a
sphere. (you do the same for the sphere)
You ask the primary class to create an instance of eachobject based on the
description outlined in their own .java file descriptions, typed out
seperately.
They place a unique set of variables and methods into memory where you can
use name.action(); to do stuff.

public class Tank{

    private int num;
   public Tank(){
        System.out.println("I am a tank."); // not very much like what a
tank would do, but ... wait
    }// end constructor of this class which makes it an object
   public int calculate(){
      num = 5;
      return num;
   } // end method: tellMe

}// end class

So, when your primary program's file code calls the tank.calculate(); and
you place the value which tank's method calculates, it hands back the int
value variable named num.

public class FileName{

   private Tank t; // here you declare to the compiler that you will make
a tank.
   private int size; // this is the declaration
   public FileName(){ // being the constructor

     t = new Tank(); // that is a call to the compiler to make room in
memory and go to the constructor of the tank to make an instance of itself
     size =t.calculate(); // this initializes the previously declared
variable with the value calculated in the tank's calculate method.
   }// end constructor

   public static void main(String [ ] arg){
      FileName fn = new FileName();
   } // end constructor

} // end class

So, here you have the means to have the main program FileName ask the Tank
class to do something and pass a value back to it.

Last, you can ask the main program to hand some value to the secondary file
in roughly the same nammer.

by adding a method in the tank file and a line in FileName:

public int calculate(int a, int b){
  int first = a;
  int second = b;
  int result = a*c;
  return result;
}// youcan add this method instead of or along with the original into the
class tank.

 int height = 55;
 int length = 60;
size = t.calulate( height, length);
 // it shouldn't take much to see that this goes in the constructor method
or any other method elsewhere in the main program file.

Your second question, in a short version (and there are many, this is just
one) requires that you declare two things:

private String reply;
private BufferedReader kb; // short for keyboard

they go where the other declared variables go, before the constructor.
Then you declare and use them inside some method:

kb = new BufferedReader(new InputStreamReader(System.in));
System.out.println("What would you tell me?"); // this is so the user has
some clue to type something.
reply = kb.readLine(); //this is a method which exists in a class you've
imported from the basic java language. When you type and hit return, it
stores it.
System.out.println(reply);

You probably want to get stuff from a file.
You would use :
private BufferedReader inF; // short for input from a file

inF = new BufferedReader(new InputStreamReader(new FileInputStream(new
File("C:\words.txt");
reply = inF.readLine(); this gives you the first line of the file
...and put things into files.
That is another question and you can use output streams to write to files

import java.io.*;
class WritingFile
{
     public static void main(String[] Args) throws Exception{
     // Create a new File object in the program
        File myFile = new File("MyFile1.txt");

     // FileOuputStream to send information to the text file
        FileOutputStream fs = new FileOutputStream (myFile);

     // The PrintStream object is able to write to the file
        PrintStream ps = new PrintStream(fs);

     // Writing to the screen
        System.out.println("Writing...");

     // Writing to the MyFile1.txt - use PrintStream object ps
        ps.println("Who let the dogs out?");
        ps.println("Whoof! Whoof! Whoof!");

    } // end main
} // end class WritingFIle
you can pull things together with:

private PrintStream ps;

ps = new PrintStream(new FileOutputStream(new File("MyFile1.txt")));

The LONG version:
What a marvelous flood of help offered by so many.
Makes one feel pleased to be part of such a well meaning group.

I am hesitant to add my response, in case someone misunderstands it to be a
flame.
.... and it is not.

It is also not off topic, just because I'm gonna mention education and
learning, and not just code and syntax.
As one who has only recently 'gotten' Java and many of its ideas, I am
keenly aware of several educational issues.
With respect to all, and especially to Nigel's details, there is a big
important understanding which has not been mentioned.

I have also experienced 'helpers' who knew what they were doing, but did not
articulate all the working parts.
Further, the question which I believe Rodrigo was asking was about the
nature of OOP.
Why bother to write something in OOP, when it can be written in a few
procedures?
If you already know how to do something in C \ C++ \ Perl etc., you might
want to realize the notion that you are doing it differently so that you can
use the new technique to do something which procedures will not not allow.

There are several reasons to write object oriented programs.
Your text 'ought to' mention and list them, but may not be specifically
said.

When you write a program you are asking some nouns to perfom some verbs upon
some other nouns.
Sometimes the subject noun is the program itself.
Sometimes you ask a method (procedure in C\C++), to adjust some variable.
You are modeling some behaviour in the 'real' world.
That can be done in procedures easily enough.

What if you have more than one?
Let's say you have two similar things or almost similar things doing things
which are close, but not exactly the same?
You could 'tweak' the description of both, inside of one description.
You would specify how the act in the way you make one.
You could make them from the same description, and just adjust the way you
ask.

For example, you could have a method (think of it the same as a procedure),
where you are going to calculate the volume, or ask the name or move it
somewhere.
You know that you might want to do this in several ways, and so you use
loops to call the same method and you let it change the variable.
You are happy that you have a method, which accepts parameters and does the
thing you've asked differently each time.
Ooops! (if you'll pardon the pun).
What if you wanted to have several of these values to remain available for
later review, or to use several in some calculation.
Sure, you can use arrays.
But, ... this raises a neat value of OOP.
When you have a series of variables in some array, and you have an array for
each thing you want to review, you need to think about how many arrays your
program will need when it grows up to be some kind of simulation.
... and then you are arranging to have an array of names, and an array of
addresses, and array of cars owned by one of the people in the first array.
.. and you need some way to think about how to keep track of which name and
which car, etc....

You have just introduced a reason to write some kind of utility like thing
to do all this for you.
Voila! You now know why to build a way to specify that you could have an
array which has all its housekeeping taken care of in the background.
... and they called them objects.

Inside of a written text file, which meets the java syntax, you describe
some variables, you make a claim about how to construct this object, and you
may name some verb like methods which which allow you to accept values
passed to it from anywhere or action to be taken by anyone who has the right
to ask, or to return some value to another class turned object which has
asked for something.
OOPS... got away from myself again. Sorry.
Sure is easy to talk jargon without introduction first.
When you write some code in a SomeFileName.java text file, and pass it to
the java compiler with javac SomeFileName.java, it is turned into a
SomeFileName.class name which you can run by asking the java runtime
environment or java machine to run with the command: java SomeFileName and
it knows that it can only run on a .class file.
All that is far too fundamental, but ... hold on. When you compile one
file, into a program, you are also making a copy of any other file referred
to inside of it.
WHOAH, when did that happen?
Well, if you can write a method so you can use it several times, and you can
customize it from inside with the values you pass it, you can consider
another class file you write in .java text form, to be like another method,
and you can pass values to it and you can customize it by asking it to
create an instance of itself .
Why is that valuable?
You can allow the housekeeping of a .class file (from a .java file), to keep
track of what is like an array of variables which are unique and clean.

When you write a procedure and you pass some values to it in the (parameter)
list, you are asking a verb to perform upon some noun, likely the one you
passed to the method.
Same thing happens when you write another .java file and compile it into a
.class file, where you have written some methods, which recieve some values
or requests.
[ Here's the concrete example section. ]
You might want to make a neighbourhood. That would be the program which has
the main method in it, to start things off.
Then you write several classes describing these other things, and that is
the art of what you want to make.
This way a series of unique people could be created, and each could have a
unique home, car or dog.
Each of these items could have a uniqued name and change things like their
age, or whether they need something like food, gas, or electricity.
You could name the action of meeting each of these needs as replenishing.
Each of the seperate items could have a private void replenish(); method
you could call.
Each of the seperate objects would act in a unique manner, which is
polymorphism.
You get to use one call from where ever and each handles it by the unique
code you wrote to simulate what that object's life represents.

So, you would only do that in procedural languages with way too much detail
re-written and not available in an event driven manner.
Especially when you place some representation of this in a gui-application
and have all the standard window availibility.

I know that I've written a lot, but for those who are just starting, there
are so many missing pieces which beg for some code examples and some
examples of what it means, and some mention of how this is tied together
with a purpose.
So, apologies to those who didn't want to read so much.
You're welcome to anyone this helped.

Now, as far as finding lots of code examples.... happy hunting.
For syntax structure:
remember that all methods have:

<access type> < return type> <method name> <parameters passed in>
<code block begins>

private int calculate (int
a, int b) {

// do whatever you want to

} // end code block

Nearly the same happens for building a method.
Once you recognize the anatomy, you can look at code snippets anywhere and
take it apart to see the unique interesting names people come up with.

Keep having fun!
S.

ps. Flaming nto requested, but... welcomed along with recipes for your
favorite slow cooker meal. I'll eat them both. Each will be amusing.



Relevant Pages

  • Re: what is the initial value of arrays of object
    ... Can I create the array with other constructor ... That does not look like Java to me. ... Anyone but Harper for Prime Minister of Canada ...
    (comp.lang.java.programmer)
  • Re: Array of Objects - Qsn
    ... alij wrote: ... I was wondering if there is a way to call a specific constructor when ... creating an array in Java. ...
    (comp.lang.java.programmer)
  • Re: Array of Objects - Qsn
    ... I was wondering if there is a way to call a specific constructor when ... creating an array in Java. ... objects without an explicit loop? ...
    (comp.lang.java.programmer)
  • Re: Array of Objects - Qsn
    ... I was wondering if there is a way to call a specific constructor when ... creating an array in Java. ... objects without an explicit loop? ...
    (comp.lang.java.programmer)
  • Re: New (as in days) to Java - question about "super()" method
    ... > Hi, I'm Don, and I'm a serious greenie when it comes to Java. ... learn Java because Object Oriented Programming is quite different from ... > guts out of the method involved (a constructor, I believe, is the ... inheritance: if I have a class and I want to add some extra ...
    (comp.lang.java.programmer)