Non-Public Class In A Source File Doesn't Matching Its Name

Oct 20, 2014

I have a question about the following snippet concerning the steps the javac compiler follows to compile a program:

[...]at first, searching a class within a package is discussed if the latter doesn't contain a full package name[...]

It is a compile-time error if more than one class is found. (Classes must be unique, so the order of the import statements doesn't matter.)

The compiler goes one step further. It looks at the source files to see if the source is newer than the class file. If so, the source file is recompiled automatically. Recall that you can import only public classes from other packages. A source file can only contain one public class, and the names of the file and the public class must match. Therefore, the compiler can easily locate source files for public classes.

However, you can import nonpublic classes from the current package. These classes may be defined in source files with different names. If you import a class from the current package, the compiler searches all source files of the current package to see which one defines the class. I don't quite understand the red fragment. I wondered if the word "import" nonpublic classes from the current package weren't a synonym for the word "use", since why would we want to import a class from the same package when compiler searches the current package automatically anyway?

However I wanted to test nonpublic classes that are contained in source file which name doesn't match the class name:

NonpublicClass.java:

Java Code:

package com.work.company;
class NonpublicClass
{
public void description() {
System.out.println("Working!");
}
} mh_sh_highlight_all('java');

[Code] ....

Everything's fine when the source file names are the same as above. However, when I change NonpublicClass.java to a different name, there's an error "cannot find symbol" in:

Java Code: NonpublicClass v = new NonpublicClass(); mh_sh_highlight_all('java');

I noticed that the class file for NonpublicClass isn't even generated so that's probably the cause. If I change to the directory of the package the NonpublicClass is contained in and compile it directly, i.e. issue for example:

Java Code: javac NonpublicClass_different_name.java mh_sh_highlight_all('java');

Then a proper class file is generated with the class name, that is NonpublicClass.class, and afterwards I can compile the main program in Start.java.

So the question is what am I missing regarding the cited quote that reads:

If you import a class from the current package, the compiler searches all source files of the current package to see which one defines the class.

? Because adding such an import to CompanyClass.java:

import com.work.company.NonpublicClass;

didn't work either...

View Replies


ADVERTISEMENT

One Public Class Per File

Feb 8, 2014

The compiler won't let me declare more than one class as "public". Am i correct in understanding that this is a java restriction ? This means i need to create a new file, for each public class that i want in a package ? The rest of the classes without access modifier will all be package-private. (Q has been asked before probably, but my search could not be narrowed).

View Replies View Related

Defining A Class In Source Code File?

Oct 9, 2014

"If you define a public class or an interface in your class, then it should match the name of the java source code file."

Does the statement above mean the following should compile fine ?

public class Animal{
public class Animal{ }
}

The author gives an example saying that if you have a class Multiple.java and in that class, you have:

public class Multiple{}, then it should compile.

But this does not compile. I tried it.

View Replies View Related

Can Access One Class Present In One Source File

Nov 3, 2014

I am having hard time to grasp the concept of java as i am beginner. according to different sources found in internet, only one class is written in one source file. and all those class can be accessed through the main class.
my question is

1.can we access one class present in one source file, through another class present in another source file [not through the class containing main method]?

2.can we create more than 1 class in same source file?is there special way to do it? i do get error always when i try to do so
3.can multiple classes contain main method? or should there be only single class containing it?

View Replies View Related

A Public Class In Sub-folder Is Not Getting Found By Another Class While Compilation

Feb 14, 2014

I was doing coding exercise from a book ('OCP Java SE 6 - Practice Exams' by Kathy Sierra and Bert Bates). I came to a question that told to demonstrate the difference between 'default' and 'protected' access rules by creating/making a directory structure and putting a couple of classes in different packages.

For this, I made a total of four classes, out of which, three classes are-Car, TestingCars, CarDimensions. (The fourth is not yet used in testing code till now, so, I am giving only the other three classes.) Their coding is given below.

Out of these classes, the classes- TestingCars and Car - are in a directory (say, FolderName). And, the class- CarDimensions is in FolderName's sub-folder.

The class 'CarDimensions' is public (and its components too are public). And, I am testing all the classes from the class- 'TestingCars'. But, this class (TestingCars) is not able to find the public class- 'CarDimensions' which is in its sub-folder and gives two 'Cannot find symbol' errors citing the class-CarDimensions. Also, If all three classes are put in one single directory, the programs work, without any error.

Coding:
Class TestingCars:class TestingCars {
public static void main(String[] args) {
Car c = new Car();
c.setType("FourWheeler");

[Code]....

I could not find why the public class- CarDimensions- is not getting found by the TestingCars class.

View Replies View Related

Why Cannot Access A Public Method From Another Class

Feb 12, 2015

Why can't I access a method from another class? For example, I want to get the value of get method from another class. It's giving me an error on if(getExamType() == 'M') That's what I've done, for example:

Java Code:

public static Exam[] collateExams(Exam[] exams){
Exam [] r = new Exam[50];
r = exams;
Exam [] finalExam = new Exam[50];
for(int i = 0; i < r.length; i++) {
if(getExamType() == 'M') {
}
}
return r; mh_sh_highlight_all('java');

View Replies View Related

How To Create Public Get And Setter Methods For Private Members Of The Class

Mar 23, 2015

If i have a class(lets say class name is Approval) with the following private members: String recip_id, Int accStat, String pDesc, String startDate How can i create public get and setter methods for these private members of the class?

View Replies View Related

Public Type (name) Must Be Defined In Its Own File

Apr 1, 2014

I have a small issue understanding the following error message that Eclipse returns when i try to run the following code:

class Film {
String tytul;
String rodzaj;
int ocena;
void odtworz() {
System.out.println("Odtwarzamy film.");

[Code] .....

The message itself reads: "Exception in thread "main" java.lang.Error: Unresolved compilation problem:

at FilmTester.main(Film.java:13)"

and the following on the line where the problem arises:

What gives? I'm positive i'm missing something obvious but i can figure it out why

View Replies View Related

Error / The Public Type Welcomer Must Be Defined In Its Own File

Mar 30, 2014

Why I cannot use 2 public classes like below?

public class Hello {
public static void main(String[] args){
Welcomer welcomer=new Welcomer();
welcomer.sayHello();

[Code] ....

Exception in thread "main" java.lang.Error: Unresolved compilation problem:

The public type Welcomer must be defined in its own file

at Welcomer.<init>(Hello.java:9)
at Hello.main(Hello.java:5)

View Replies View Related

Can A Class Be Broken Into Multiple Source Files?

Apr 3, 2014

The problem is what to do when the source file for a class gets too big ( a judgment call for sure). Is it possible for one class to be defined in multiple files and if so how do you do it, and is it good practice?

I do see ways to refactor into a base class or move code into a helper class but sometimes the abstraction is cleaner as a single class that does a lot of stuff. My problem is how to organize a BIG class?

View Replies View Related

Extract File In Same Directory As Source File

Jun 13, 2014

This is a snippet code that im developing. (no source of it) . I am facing a trouble to extract file in the same directory as the source file (example: extract here option)

public class HelperAction {
public static void unzip(String zipFilePath)throws IOException {
File dir = new File(zipFilePath.substring(0,zipFilePath.length()));
// create output directory if it doesn't exist
if(!dir.exists()) dir.mkdirs();
FileInputStream fis;

[Code] ....

View Replies View Related

Copying From One File (source) To Another File (destination)

Jul 5, 2014

I have a file(source.txt) that contains some texts. Now, the java code is to run through each line in the source file and check if that line begins with a number and if true, copy that line to the destination file(destination.txt). I have the code but I am not sure why I can't loop through each line in the source.txt file. Below is my java code:
 
public static void copyFile(File source, File destination) {
BufferedReader br;
try {
FileWriter fw = new FileWriter(destination.getAbsoluteFile());
PrintWriter bw = new PrintWriter(fw);
br = new BufferedReader(new FileReader(source));
String line = new String();

[Code] ....

As shown in the source.txt file, there are 4 lines in the file but when the execution gets to while ((line = br.readLine()) != null) , it executes to false.. Why this is so?

below is the source.txt file

12 is a number
Green is bad
5 is not so cool
you are right

View Replies View Related

Add Source To Bat File?

Aug 30, 2014

Have the following .bat file that compiles the ReadMindWave.java source with jna and jfreechart. I get a javac error saying 'no source' when the .bat is run, as the .java source needs to be included in the .bat file. Where it goes in the following .bat file?

@echo off
echo Compiling %1 with JNA and JFreeChart...
javac -Xlint:deprecation -cp "C:jna-master*;C:jfreechart-1.0.19libjfreechart-1.0.19.jar;C:jfreechart-1.0.19libjcommon-1.0.23.jar;."%*

The file to compile is in C:MindWaveTestsReadMindWave.java

View Replies View Related

Finding Source Files In Other Directory With Class Path Option

Apr 23, 2015

I'm having another issue. I have 2 java source files(see below). They are place in the same directory. How do I compile them using classpath?

I have already tried 1st attempt :

javac -cp com.companyname.interview.DuplicateReplace.java DuplicateReplaceTest.java [did not work!]
2nd attempt: javac -cp DuplicateReplace.java DuplicateReplaceTest.java [again, did not work!]
package com.companyname.interview;
public class DuplicateReplace { /* code */}

[Code] ....

View Replies View Related

PrintWriter Creates File But Doesn't Print File

Nov 7, 2014

This is a college course assignment that consists of classes TotalSales and TotalSalesTest.In the main program I have created a two dimensional array to output a columnar layout with cross-totals in 4 rows and 5 columns. This program outputs sales totals by row for each sales person(1 - 4) and output by column for products(1 - 5). I have created extra elements in the array to store total for rows and columns. So far both classes compiles. The problem is that although the PrintWriter creates a notepad file, it doesn't print to it. I don't seem to understand the input and output methods completely. I finished another program similar to this using basically the same try and catch that read the file and printed out a document in notepad. Here is the code and I'll try include the input file.

import java.util.Scanner;
import java.io.*;
public class TotalSales {
private int salesPerson; //declare class variable
private int productNumber;//declare class variable

[code]....

View Replies View Related

Source File Input

Jun 8, 2014

how to add an error message when my program can't find the file the user inputs.

For example:

Enter your source code:
D:Data StructsProjectssrcHelloWorld (I didn't put .java on purpose)
Exception in thread "main" java.io.FileNotFoundException: D:Data StructsProjectsAssignment 3srcHelloWorld (The system cannot find the path specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileReader.<init>(Unknown Source)
at HomeworkDriverFour.main(HomeworkDriverFour.java:14)
//Can I get rid of the exception above and replace it with "File not found!"

Enter your source code:This is what I have so far:

import java.io.*;
import java.util.*;
public class HomeworkDriverFour {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub

[code]...

View Replies View Related

Source File Compilation

Jan 22, 2015

when i try to compile following source file, there is a error which states "MovieTestDrive is public, so must be declared in a file MovieTestDrive.java" i didnot understand. i am beginner in java;

class Movie
{
String title;
String genre;
int rating;
void playit()
{
System.out.println("playing the movie");
}
}

public class MovieTestDrive

[code]....

View Replies View Related

Using Enumeration Of One Source-code File In Another?

Mar 30, 2014

To be specific, how can I use enumeration of one source-code file in another.

View Replies View Related

Source File - Arithmetic Operator Substitution

Nov 6, 2014

My goals:

1) Have some source file be read in

2) Specify what arithmetic operators to swap (+, -, /, *)

2) If an arithmetic operator is read (like a + sign etc) then we swap it with its opposite (- for example)

3) Once the swap is complete, the rest of the file stays the same even if more operators are in the file...it is then output to a file (I am going with 1mutation.java)

4) This is where it gets tricky....it then picks up where it left off to finish reading the + operators (or whatever was specified) and repeats steps 2-3 (but the operator that is already swapped gets left as it was / skipped) and the output is saved as 2mutation.java.

The most I have been able to manage is having it changed 1 operator or all of them at once. I deleted a lot of my work to start fresh / master one operator for the time being. Here is what I have:

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
 
public class OperatorSub {
 
[Code] ....

This is the data file I am using. (see attached) The file should be .java or .cpp but I stuck with .txt for now. How to tackle this? Am I on the right track?

View Replies View Related

Text From The Class Game Doesn't Update

May 3, 2014

I have a main class that hold the frame and paints, a class for drawing my game, and an image that is drawn too.
I want to count the amount of times I click on this "android" (right now it counts if i click the screen) but the text from the class Game doesn't update.

androidX = Main.width - android.getWidth();

doesn't work. In my head the image should be inside the borders but it isn't. Have I calculated the pixels wrong or am I missing something?

public class Main extends JPanel{
public static final int width = 600;
public static final int height = 600;
Game game = new Game();
Android android = new Android();
public void paint(Graphics g) {
super.paint(g);
game.render(g);
android.render(g);

[code]....

View Replies View Related

Swing/AWT/SWT :: Loading Image File From Source Directory?

Jan 25, 2014

My problem is that I want to load an Image from the source directory in Canavas' paint() method.

My code is currently (in a try/catch)

g.drawImage(ImageIO.read(new File(imageLocation)), imageX, imageY, null);

Where imageLocation leads to an image on my HDD ("C:UsersVladdeDocumentsFolders-Filesfolder.png")

View Replies View Related

How Java Finds Jar Contents Imported In A Source File

Feb 10, 2015

how java imports libraries from a jar file inside a source. Let's say I have the following code on Something.java file,

import com.mycomanyA.*;
import com.mycomanyB.*;
public class Something{
public static void main(String ... args){
// code goes here...
}
}

And the Something.java is inside the following structure...

A.jar
com/
mycompanyA/
A.class
Another.class
B.jar
com/
mycompanyB/
B.class
neededImage.gif
bin-folder/
org/
apache/
Something.java

To compile this code(Something.java) from command line I want to use the following command,

javac org/apache/Something.class

And for the compilation to be successful, I'll have to be just above bin-folder because...

- > Only then my default class path will be (.) and java would automatically include A.jar and B.jar(the other way is to add the jar files using -cp argument, which I want to avoid in this scenario)

- > And for the import org.mycompanyX to work I'll have to be in the (.) directory.

Are my assumptions correct about how java find jar contents imported in a source file?

View Replies View Related

Jar File Doesn't Run

Dec 13, 2014

so i followed a tutorial on youtube called "Java Game Development with Slick" - by thenewboston,URL....okay, so i have made my game / program, and now i just want to export it to a jar file that people can double click and play..unfortunately when i double click the .jar file nothing happens...i get the little "loading" thingy on my courser but it disappears after about 5 seconds and then nothing happens :(the way i made it into a jar file is by doing the following:

-right clicked my java project..
-clicked on "export"..
-clicked on java / Runnable JAR file
-filled in the stuff, (JARs destination ect..)
-pressed finish..
-then i got a jar file on my desktop and double clicked it....but as i said....nothing happens

View Replies View Related

Java Source Code File Naming With Access Modifiers

Feb 3, 2014

Why is this not valid in java:

Both uses public with the same class/interface name.

Test.java:
public class Test implements Test{
/// Some codes
}
public interface Test {
///Some methods
}

View Replies View Related

Read In Java Source Code File As Command Line Argument

Oct 31, 2014

I am trying to complete this question. I understand the most of it but I haven't go a clue to read in the file name.

Full question: Implement a program that reads in a Java source code file and checks to see if it has balanced {}brackets. Your program should use a stack, implemented as a linked list, to check the brackets.

NOTE: you can use a reference called top which points to the head of the list. Your program should run as a command line program and should take a filename as an argument and print one of BALANCED or NOT BALANCED.

For example: c:> java checkBalanced "myProgram.java" BALANCED

View Replies View Related

Doesn't Rename File Even Though It Hits Code

Oct 21, 2014

I have two files - I can get the second one to populate with the first ones data and then delete the first one. I cannot get it to then rename itself to the name of the first file. It also only hits the 'rename' section of the code providing I place system.gc in otherwise it completely skips it.

the code I use is below:

Java Code:

finally{
try {
br.close();

// mp br.close();
//mp System.gc();

[code]...

View Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved