Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

class As A Data Type

 
Jaydeep Singh
Ranch Hand
Posts: 43
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Everyone,

When do we need to use a class name as a data type.
Thanks in advance.
jaydeep
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
Nick
 
Jaydeep Singh
Ranch Hand
Posts: 43
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
jaydeep

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
System.out.println(array[i].firstString);
if (array[i].secondString == null){
continue;
}
// process second string
System.out.println(array[i].secondString);
}
}

}
 
Carl Trusiak
Sheriff
Posts: 3341
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic