Java Classes

Posted in Code by Tieson | geeksneversleep.com

Nov

21

2008

If you are familiar with creating classes in C/C++, I have some good news and some bad news...

Good news: The concept of classes is the same in every OOP language, so you're at least one step ahead of new programmers.

Bad news: The syntax you used in C/C++ is different enough that you're probably going to spend a lot of time cursing at the Java compiler...

Similarities

Java is loosely based on C++, and implements OOP is more or less the same way. You can implement your code logic (say, from pseudo-code or UML diagrams) without much trouble, even if it was developed with specific C++ libraries in mind, as an equivalent library is probably available in the JRE (Java Runtime Environment).

Differences

While Java takes quite a bit of its base syntax from C and C++, it IS a different language, with its own quirks and strengths. One of the things that confused me when I first started to learn Java was the keywords it uses for its class structure. For instance, instead of namespace,Java uses package. Instead of inherits, you get extends.

Take a gander at this sample I put together for you:

• SampleClass.java

class SampleClass
{
   public SampleClass( void ) // constructor
   {
   /* place code here that needs to execute
   when an instance of our class is created */
   }

   // private internal variables and functions go here
   private int age;
   private char[] name = new char[50];

   /* public shared variables and external functions
   go here */
   public int GetAge( void )
   {
     return age;
   }

   public void SetAge( int value )
   {
     age = value;
   }
}

The low-down...

This is a prototype for a java function/method:

return type function-name ( parameter type parameter-name )


Updated: Never.

Tags: Java , class , snippet

Back to top Comments ( 0 ) • Login to comment.

Sorry. There are currently no comments for this article.