Sunday, August 2, 2009

Urgent Reply is needed all Java Programers...?

If I am writing the following code :--


class MyDate


{


public int dd,mm,yy;


public MyDate()


{


dd=mm=yy=0;


}


public MyDate(int d,int m,int y)


{


dd=d;


mm=m;


yy=y;


}


public void display()


{


System.out.println("Date is"+dd+"/"+mm+"/"+yy);


}


public static void main(String args[])


{


MyDate d=new MyDate(12,12,12);


d.display();


}


}


this code is written in one file or say application.


Now I am creating new file MyDemo.java and i want to use the MyDate class without using Inheritance Concept....


class MyDemo


{


public static void main(String args[])


{


MyDate d=new MyDate(12,12,12);


d.display();


}


}





This will be my code. But now the problem is that it showing me some error. And the error is -------


Now





C:\%26gt;javac MyDemo.java


MyDemo.java:5: cannot resolve symbol


symbol : class MyDate


location: class MyDemo


MyDate d=new MyDate(12,12,12);


^


MyDemo.java:5: cannot resolve symbol


symbol.

Urgent Reply is needed all Java Programers...?
You don't need this code:


public MyDate()


{


dd=mm=yy=0;


}





it is redundant since you have a constructor which is taking your 3 parameters.


So you class should look like this:





public class MyDate


{


private int dd,mm,yy = 0;





public MyDate(int d,int m,int y)


{


dd=d;


mm=m;


yy=y;


}





public void display()


{


System.out.println("Date is "+dd+"/"+mm+"/"+yy);


}





public static void main(String args[])


{


MyDate d = new MyDate(12,12,12);


d.display();


}


}





You second class will compile fine then and in typical Java naming convention class names start with a small cased letter and then the first letter of each subsequent word is capitalised (eg myDate, myDemo).
Reply:Method 1:


First compile the first file say application.java, the following class file will be created.


MyDate.class





If the file is in the same directory where the second file is there, then your program will work fine.





Method 2:


If you store the first file in another directory say for ex: "lib", add the following line in the first file at the top of the file.


package lib;





And compile the file javac -d application.java





And in the second file, add the following line at the top of the file.





For further reading, check the following reference
Reply:which line of the code does the error highlight?
Reply:Both MyDate and MyDemo must be in the same package. Just put following line at the top of MyDate.java and MyDemo.java and re-compile your code:





package mypackage;





It should work now.

surveys

No comments:

Post a Comment