The moose likes Beginning Java and the fly likes class As A Data Type Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "class As A Data Type" Watch "class As A Data Type" New topic

class As A Data Type

Jaydeep Singh
Ranch Hand

Joined: Oct 02, 2000
Posts: 43
Hi Everyone,

When do we need to use a class name as a data type.
Thanks in advance.
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
When you want to create an instance of that class. For example, if you wanted to create a new swing button, you would have to use a line of code like this:

In this case JButton describes the type of object being created, and in that sense, the class name is sort of like the data type for this object.
Jaydeep Singh
Ranch Hand

Joined: Oct 02, 2000
Posts: 43
Hi Nick,
I will appreciate your help, Here I am giving you a sample class, which I got just from here(javranch), nothinh is wrong in this code.
But I am little bit not clear the usage of class concept. I do understand about the instantiation of JButton class.
In the following code, I have two class here, which class name should be the same file(Source Code) name and why ??? we are instantiating class as an array.
There was no other way to do this task.

Thanking you with Regards.

class TwoStrings{
String firstString;
String secondString;
TwoStrings(String s1, String s2){
firstString = s1;
secondString = s2;
//public class Test{
public static void main(String args[]){
TwoStrings array[] = new TwoStrings[5];
array[0] = new TwoStrings("one", "I'm the first string.");
array[1] = new TwoStrings("two", "I'm the second string.");
array[2] = new TwoStrings("three", null);
array[3] = new TwoStrings("four", "I'm the fourth string.");
array[4] = new TwoStrings("five", null);
for (int i = 0; i < array.length; i++){
// process first string
if (array[i].secondString == null){
// process second string

Carl Trusiak

Joined: Jun 13, 2000
Posts: 3340
Java allows multiple class definitions in a single source file with the following requirements.
There can only be one public class defined.
The file name must match the name of the public class.
When no public class is included in the file, it can be any of the classes. A good rule is to name the file the name of the initiating class or the one with the main method, though this isn't a requirement.

I Hope This Helps
Carl Trusiak, SCJP2, SCWCD
I agree. Here's the link:
subject: class As A Data Type
jQuery in Action, 3rd edition