Forums Register Login

What is the generally structure/form/outline of a Java code?

+Pie Number of slices to send: Send
Hello all!

Could some detail the basic structure and outline that Java code follows. I know that Java code opens with a class and a bracket then after the class comes the main and a bracket then a lot of 'stuff' follows which I do not understand yet. Generally speaking, what sort of code goes immediately after the class bracket? And generally speaking, what sort of code goes after the main method bracket?


Thank you
+Pie Number of slices to send: Send
I generally go with the following, though it is mostly my style, I ask my teams to do the same:


I do not encourage anonymous classes, as they quite often are missed or not understood by new programmers. Indentation at 2 spaces per indent, no empty lines except to separate significant logic and process.
+Pie Number of slices to send: Send
@Les Morgan That's great set up! and from what I've been reading a lot of code seems to go in that order. So generally speaking, all the static and instance variables go within that area right after that first class bracket? then the constructor. Then the Main method, I understand that to be the entry point of the program, or the starting point. Are the methods generally after the main method? I may be mistaken here but I think I've seen them possibly declared right after the class bracket? Could you explain what constructors and inner classes are?

Thank you!
+Pie Number of slices to send: Send
I'm currently in Java II, but when I started in Java I the professor told us to use "buckets" to keep things organized.

The first is variables
Second is input
Third is calculations
Fourth is output

For the first few assignments we had to make comments separating each 'bucket' as best we could.

Here's an old assignment in which I used that method:



Not sure if this helps, but I suppose it could be useful if you're just starting out.
+Pie Number of slices to send: Send
Yes, after the class header the static variables are listed first, then the instance variables.
Java is a little more free style in it's layout than I care for--yes, I'm a control freak--so as I said the layout that I showed is mainly my style that I have come to settle upon. I have seen things laid out in a few ways, but I like to see what I'm going to use before I get there or have a logical and predefined way of looking for things.

Constructors are special methods that shape the class when it is instantiated. You can do any initialization you need here or customizations as need to the resulting object.

inner classes are classes that are defined as a whole inside another class. They inherit the environment of the parent class, as they are, in actuality, part of that parent class.

Justin Robbins wrote:@Les Morgan That's great set up! and from what I've been reading a lot of code seems to go in that order. So generally speaking, all the static and instance variables go within that area right after that first class bracket? then the constructor. Then the Main method, I understand that to be the entry point of the program, or the starting point. Are the methods generally after the main method? I may be mistaken here but I think I've seen them possibly declared right after the class bracket? Could you explain what constructors and inner classes are?

Thank you!

 
+Pie Number of slices to send: Send
 

Les Morgan wrote:Yes, after the class header the static variables are listed first, then the instance variables.
Java is a little more free style in it's layout than I care for--yes, I'm a control freak--so as I said the layout that I showed is mainly my style that I have come to settle upon. I have seen things laid out in a few ways, but I like to see what I'm going to use before I get there or have a logical and predefined way of looking for things.

Constructors are special methods that shape the class when it is instantiated. You can do any initialization you need here or customizations as need to the resulting object.

inner classes are classes that are defined as a whole inside another class. They inherit the environment of the parent class, as they are, in actuality, part of that parent class.

Thank you!



Ok, class header is the part with the brackets. Then comes the static first and then instance variables. I actually like this style, and may have come to it naturally actually. I've seen a lot of YouTubers use it. The inner classes part, so we set up the environment of one class say it's cats and it has the static variable hair and legs, don't know if I am saying that right. But then after that we subsequently create a new class on the very same page called dog, so since cats and dogs share similar things we can sort of branch off and take bits and pieces of the static parts of cat and apply them to dogs? Is that right? Still a little confused on the basics.
+Pie Number of slices to send: Send
 

Nikki Smith wrote:I'm currently in Java II, but when I started in Java I the professor told us to use "buckets" to keep things organized.

The first is variables
Second is input
Third is calculations
Fourth is output

For the first few assignments we had to make comments separating each 'bucket' as best we could.

Here's an old assignment in which I used that method:



Not sure if this helps, but I suppose it could be useful if you're just starting out.



Thank you so much Nikki! I copied this and put it in my Eclipse workspace for future reference. I wish my teacher would make us outline things like this. The whole idea of buckets is wonderful. Cannot imagine what else he taught you guys. Any other tips/tricks he showed you when learning Java I? Still ify about the difference between Static variables/methods and Instance variables/methods and exactly what they do.
+Pie Number of slices to send: Send
The only other thing he makes us do, aside from documentation in the header, is make pseudo code for every assignment. He tells us to make that first so that we can make sure we actually understand what we're going to do and how we plan to do it. This is the pseudo code I made for the code I posted above.

Purpose - calculate the take home pay after income tax is subtracted

Input - User is prompted to input their name, age and income

Process - The name and age are each stored in separate variables that are
returned as-is except that the name is displayed in lowercase
income * taxRate finds the income tax ammount and stores it in incomeTax
takeHomePay = income - incomeTax

Output - Users name, age, income, income tax and take home pay are displayed



simple pseudocode:
create keyboard scanner to obtain input
obtain input name, age, income
calculate incomeTax = income * taxRate;
calculate takeHomePay = income - incomeTax;
display user-defined name, age, income and post-calculation income tax amount and take home pay

detailed pseudocode:
create keyboard scanner to obtain input
prompt user for their name
obtain user name
prompt user for their age
obtain user age
prompt user for their income
obtain user income
determine incomeTax = income * taxRate;
determine takeHomePay = income - incomeTax;
display user-defined name, age, income and post-calculation income tax
amount and take home pay on separate lines




We also had to learn 9 steps listed out in our book as a helpful guide of sorts
The book we're using is "Starting Out With Java - From Control Structures Through Objects - 6th edition"

The 9 steps it lists are as follows:

1) Clearly define what the program is to do
2) Visualize the program running on the computer
3) Use design tools to create a model of the program
4) Check the model for logical errors
5) Enter the code and compile it
6) Correct any errors found during compilation and repeat steps 5 and 6 as necessary
7) Run the program with test data for input
8) Correct any runtime errors found while running the program and repeat steps 5 through 8 as necessary
9) Validate the results of the program


All through Java I he only allowed us to use plain old MS Notepad text editor for coding to make us work harder to find our errors and not have the luxury of auto-complete or anything like that. In Java II we can use any editor we chose.
+Pie Number of slices to send: Send
Nope, that is generally not how it works.

OK... everything in Cat is part of Cat. Leg inherits furColor from Cat, but legColor is in the class Leg which is an inner class of Cat. Dog is a separate class from Cat, but contained in the same file.

Please NOTE: none of the code was run through any checks, so it may or may not be totally accurate.
+Pie Number of slices to send: Send
 

Les Morgan wrote:Nope, that is generally not how it works.

OK... everything in Cat is part of Cat. Leg inherits furColor from Cat, but legColor is in the class Leg which is an inner class of Cat. Dog is a separate class from Cat, but contained in the same file.

Please NOTE: none of the code was run through any checks, so it may or may not be totally accurate.



I've never seen classes within classes like that, so I'm not really sure about that. When we have to make programs and use classes we have to spread it out across several different files. Usually the main file thats called is usually titled SomethingDemo and then each of the classes we make for the Demo are different files with related names. My book describes classes as "A blueprint". Basically you can set up a class in a generic way and then you can use it anytime and anywhere you need it rather than having to keep typing the same code over and over in different places in the same file.

One of our assignments was to create a CoinDemo and a Coin class.

Basically the CoinDemo class is where all the user input was sent through arguments and parameters to Coin and from there it made a new coin based on input.
The CoinDemo prompted the user to enter input and created new instances of the Coin class.

So each time the user entered a value and gave it a name, it made a new coin through the Coin class and each one had it's own value and name. The Coin class made coin objects. It was a blank coin 'blueprint'.
With the program I could input "Penny" for the name and ".01" for the amount and then I could make another and name it "Shiny" and give it a value of ".007"

Coin would then create two objects, one for "Penny" which was worth ".01" and one for "Shiny" with the value of ".007"

The Oracle website has an example using Bicycle and BicycleDemo.
+Pie Number of slices to send: Send
Also, main method should be in separate class.
+Pie Number of slices to send: Send
Classes inside of classes are very common, at some point you are going to have to progress past the static framework of working in the main method, and when you do, you are going to see Java come alive.

Here is just a little tidbit that I like to play with for animation. The basic game container is made of a class with an inner class and the ships (not completed) are listed in the same file, but not as part of the same class.
1
+Pie Number of slices to send: Send
You will find suggestions about order of where you write your code here and here (latter link very dated).
Agree about restricting the number of empty lines. One empty line to separate succesive methods, etc. Number of spaces per indent: depends which book you have read. Google require 2 spaces.

Disagree.
Don't write your methods in alphabetical order, but group them by type. So if you have pairs of getXXX and setXXX methods put them together.
getXXX setXXX getYYY setYYY getZZZ setZZZ
Don't put classes in the same file in alphabetical order but group them logically. If you have any difficulty grouping them, they should not be in the same file.

Disagree.
Don't write lots of comments which simply repeat what the code says. String name followed by a comment to say that you have a String to store the name is a waste of keystrokes an should not be written. Nearly all those comments in NS' example ought to be deleted because they only tell you what you know already. Comments should be as long or as short as is necessary and they should always explain things which are not already obvious. Avoid multiple symbols in comments, unless you intend them to be displayed on screen. No /*-----------comments-------------*/ please. // comments must be very short because they need to fit at the end of the line.

None of you has written any documentation comments. You may not have time to write documentation comments if you are writing a class in a teaching session, but all non‑private class members and constructors should be preceded by /** comments */. Writing documentation comments is a skill in itself. You can find about it here and in Effective Java™ by Joshua Bloch.
+Pie Number of slices to send: Send
 

Justin Robbins wrote:Thank you so much Nikki! I copied this and put it in my Eclipse workspace for future reference. I wish my teacher would make us outline things like this. The whole idea of buckets is wonderful.


I don't want to criticise Nikki or her teacher, but I feel I ought to point out that the system has a acronym: IPO (for Input-Process-Output), and dates back to the 1960's, when programs were usually large, monolithic blocks of code.

And while I have no problem with any methodology that helps you organise, or forces you to think before you code, I'm not sure that it's the best fit for an Object-Oriented language like Java. It's essentially a way to think about processes or 'functions', and Java tends to work best with objects.

While you're starting out, it's perhaps not a bad discipline to use; but IMO Nikki's example main() method is at least five times as big as it should be (not counting comments), and is missing at least two classes - the main one being Person (or WageEarner).

So: by all means use it to organise your thoughts and document your code - both of which are extremely important - but if you're writing methods that are so big that they need this sort of organisation, then they are almost certainly TOO big.

HIH

Winston
Well THAT's new! Comfort me, reliable tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 595 times.
Similar Threads
Question about software structure
Java Style Guide
HeadFirst DotComBust... Help?
First Factory Methods
help
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 29, 2024 08:42:50.