Hi
HERE is mu program .. it works fine no problem with that .. but it only compiles when i remove public specifier from the class " Horsetest" .. why is this happening ?? any ideas .. in c# if we declare like this program will execute no compile error .. why
Program :
public class HorseTest
{
public static void main (String [] args)
{
class Horse
{
public String name;
public Horse(String s)
{
name = s;
}
}
Object obj = new Horse("Zippo");
Horse h = (Horse) obj;
System.out.println(h.name);
}
}
please help me :) cheers
Loading


VulpesRank #55 · 29.2K reputationPosted Oct 26, 2013, 3:28 PM EDT
SUNIL GUTTARank #1,831 · 810 reputationPosted Oct 26, 2013, 3:39 PM EDT
So public to the above code is nothing to do with main method ..
My friend said if a class contains a main method in it it is called main class .. then the main class should'nt be public must he said ?? ..
is he right ..
Thank you
SUNIL GUTTARank #1,831 · 810 reputationPosted Oct 26, 2013, 3:46 PM EDT
java program is bit confusing compared to c# ..
In c# we rarely declare a class in side a class right ?
what were these name spaces in c# called in java ?? does they exist ?
TY
VulpesRank #55 · 29.2K reputationPosted Oct 27, 2013, 1:19 AM EDT
Even if the 'main class' isn't public, it's still considered good practice to give the file the same name as the class.
Although I'm not keen on the practice personally, it's not uncommon to nest classes within other classes even in C#.
However, one thing you can do in Java but not (thankfully) in C# is to nest a class within a method as you did in your example.
Java has packages rather than namespaces which fulfil the role of avoiding name collisions and some other things besides.
SUNIL GUTTARank #1,831 · 810 reputationPosted Oct 27, 2013, 1:46 AM EDT
but small thing .. when i tried to compile online .. its showing compile error when keeping public to class ..
why is it ..
VulpesRank #55 · 29.2K reputationPosted Oct 27, 2013, 5:10 AM EDT
Certainly, my desktop Java compiler isn't bothered whether the main class is public or not as long as the file name and class name are the same.
What error message do you get?
SUNIL GUTTARank #1,831 · 810 reputationPosted Oct 27, 2013, 10:38 AM EDT
VulpesRank #55 · 29.2K reputationPosted Oct 27, 2013, 10:52 AM EDT
So, when you use that site to compile your Java source code, I'd avoid using public classes.
SUNIL GUTTARank #1,831 · 810 reputationPosted Oct 27, 2013, 10:58 AM EDT
One final question in this post ..
Well you said when we keep the file name same as class name (which is fallowed in Real time)
in java the clas can be made as public right ,,
What if i made a c# code file with class public and different file name .. but still it is executing perfectly ?? any reason or am i wrong . .
cheers & ty for ur continued help
VulpesRank #55 · 29.2K reputationPosted Oct 27, 2013, 11:04 AM EDT
SUNIL GUTTARank #1,831 · 810 reputationPosted Oct 27, 2013, 11:06 AM EDT