Powered by Blogger.

Java Source File | Source File Layout Program

A Java technology source file declares firstly package statement (only one package), secondly import statements, and finally classes. Which are following bellow:

1. package <topPackageName> .[< subP ackageName >];
2. import<packageName> .[subP ackageName]*;
3. <classDeclaration>*

The package statement is a way to group related classes. The package statement place at beginning of the source file and only one package statement declaration is permitted. If a Java technology source file does not contain a package declaration then the classes declared in the file belong to the default package. The package names are hierarchical and are separated by dots. The package name to be entirely lower case.

           The import statement is used to make classes in other packages accessible to the current class. Normally, the Java compiler places the .class files in the same directory as the source file present. We can reroute the class file to another directory using the -d option of the javac command (javac -d. ClassName.java).

1 package bankingPrj;
2
3 public class Account{
4 public String accountName = ”Saving Account”;
5
6 public void showAccName( ){
7 System.out.println(accountName);
8 }
9
10 public static void main (String [ ] args ){
11 Account acc = new Account ( );
12 acc.showAccName( );
13 }
14 }

To compile this code, open a command window or terminal and change to the directory where the program is saved and type javac -d. Account.java then a package or folder will be create in the same directory named bankingPrj. Now you can run this Account.class file in bankingPrj package by typing the command java bankingPrj.Account;

1 package bankingPrj;
2
3 import bankingPrj.Account;
4
5 public class Coustomer{
6 public String name = ”James Bond”;
7
8 public static void main (String [ ] args ){
9 Account acc = new Account ( );
10 acc.showAccName ( );
11 Coustomer cous = new Coustomer ( );
12 System.out.println (cous.name);
13 }
14 }

Similarly, we can compile and run this code.

Line 3 we import the Account class from bankingPrj package.

Line 9 we create object of Account class.

Line 10 we call the method of Account class.

0 comments:

Post a Comment