Java Package Class Path and Access protection

Tuesday, 13 November 2012
How to Set the Class Path:

The classpath is a user defined environment variable that is used by Java to determine where predefined classes are located. It tells the java tools and applications where to find user-defined classes. The syntax to set the classpath is shown as:

C:> set CLASSPATH=%classpath%;classpath1;classpath2.....

You can set multiple path entries that are separated by semi-colons.
To make this thing more understandable, let's put the "HelloWorld" class along with its package "mypackage" under the "C:\mainpackage" directory. Thus the directory structure for this package is shown as:




Now we have changed the location of the package from C:\mypackage\HelloWorld.java to C:\mainpackage\mypackage\HelloWorld.java. Then the CLASSPATH  needs to be changed to point the new location of the package mypackage accordingly shown as:

set CLASSPATH = .;C:\mainpackage;

Although in such condition, Java will look for java classes from the current directory instead of the "C:\mainpackage" directory.


Access protection in packages:

 Access protection  Discription
 No modifier (default)  The classes and members specified in the same package are accessible to
all the classes inside the same package.
 public  The classes, methods and member variables under this specifier can be accessed from anywhere.
 protected  The classes, methods and member variables under this modifier are accessible by all subclasses,
and accessible by code in same package.
 private  The methods and member variables are accessible only inside the class.


Access to fields in Java at a Glance:

Access By public protected default private
The class itself Yes Yes Yes Yes
A subclass in same package Yes Yes Yes No
Non sub-class in the same package Yes Yes Yes No
A subclass in other package Yes Yes No No
Non subclass in other package Yes No No No

Java package Features and rules for use

Features of a Java package
  • The protected members of the classes can be accessed by each other in the same package.
  • It resolves the naming collision for the types it contains.
  • A package may have the following types.
    • Interfaces
    • Classes
    • Enumerated types
    • Annotations

Naming convention (Rules) for using  the packages
  • Package names are written in all lowercase to avoid conflict with the names of classes or interfaces.
  • The directory name must be same as the name of package that is created using "package" keyword in the source file.
  • Before running a program, the class path must be picked up till the main directory (or package) that is used in the program.
  • If we are not including any package in our java source file then the source file automatically goes to the default package.
  • In general, we start a package name begins with the order from top to bottom level.
  • In case of the internet domain, the name of the domain is treated in reverse (prefix) order. 

Simple java Package program for beginners

Simple java Package program  for beginnersTo create a package is quite easy ,simply include a Package command as the first statement in a java source file.Any classes declared  within that file will belong to the specified package.The package statement defines a name space in which classes are stored.If you omit the package statement ,the class names are put into the default package ,which has no name .while the default packages is fine for short ,sample program it is inadequate for real applications .Most of the time ,you will define a package for your code.


Given that packages exist and are a good mechanism for compartmentalizing diverse classes from each other, it is easy to see why all of the built-in Java classes are stored in packages. There are no core Java classes in the unnamed default package; all of the standard classes are stored in some named package. Since classes within packages must be fully qualified with their package name or names, it could become tedious to type in the long dot-separated package path name for every class you want to use. For this reason, Java includes the import statement to bring certain classes, or entire packages, into visibility. Once imported, a class can be referred to directly, using only its name. The import statement is a convenience to the programmer and is not technically needed to
write a complete Java program. If you are going to refer to a few dozen classes in your application, however, the import statement will save a lot of typing.

This is the general form of the package statement
 package pkg;

eg :
package  PackageName;

In a Java source file, import statements occur immediately following the package statement (if it exists) and before any class definitions. This is the general form of the import statement:

import pkg1[.pkg2].(classname|*);


Here, pkg1 is the name of a top-level package, and pkg2 is the name of a subordinate package inside the outer package separated by a dot (.). There is no practical limit on the depth of a package hierarchy, except that imposed by the file system. Finally, you specify either an explicit classname or a star (*), which indicates that the Java compiler should import the entire package. This code fragment shows both forms in use:

import java.util.Date;
import java.io.*;


How to compile and execute java package


1)Create Folder Example

2)Create another directory inside Example named Mypack

3)Copy the file example.java inside mypack

4)Exit from Mypack directory and open Example directory

5)copy the file exampletest.java file inside Example directory

6)open cmd and compile  all the java file

7)Run the exampletest.java file


Program :example.java
file path :C:/Java/mypack/example.java

package mypack;
public class example
  {
   public String test(String str)
    {
       return str;
    }

  }
Program :exampletest.java
file path :C:/Java/exampletest.java

import mypack.*;

class exampletest
{
  public static void main(String args[])
   {
   example obj = new example();
   System.out.println("Return value "+obj.test("vineeth"));
   }
}

Output

C:\java>java exampletest
Return value vineeth

Simple java Package program for compile and run beginners

The object class in java Programming

Monday, 12 November 2012
There is one special class object defined by java , All other classes are subclasses of object ,That is object is a superclass of all other classes .This means that a reference variable type object can refer to an object of any other class .Also since array are implemented as classes a variable of type object can also refer to any array

Object defines the following a method ,which means that they are available in every object


Method
Purpose
Object clone() creates a new object that is the same as the object cloned
boolean euals(Object obj) Determines whether one object is equal to another
void finalize() called before an unused object is recyled
Class getClass() Obtains the class of an object at run time
int hashCode() Returns the hash code associated with the invoking object
void notify() Resumes execution of a thread waiting on the invoking object
void notifyAll() This method wakes up all threads that are waiting on this object's monitor.
String toString() This method returns a string representation of the object.
void wait() This method causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object.
void wait(long timeout) This method causes the current thread to wait until either another thread invokes the notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed.
void wait(long timeout, int nanos) This method causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object, or some other thread interrupts the current thread, or a certain amount of real time has elapsed.

Example of Final variable, Final method and Class in Java


Final in java is very important keyword and can be applied to class, method, and variables in Java. In this java final tutorial we will see what is final keyword in Java, what does it mean by making final variable, final method and final class in java and what are primary benefits of using final keywords in Java and finally some examples of final in Java. Final is often used along with static keyword in Java to make static final constant and you will see how final in Java can increase performance of Java application.


Final keyword in java can also be applied to methods. A java method with final keyword is called final method and it can not be overridden in sub-class. You should make a method final in java if you think it’s complete and its behavior should remain constant in sub-classes. Final methods are faster than non-final methods because they are not required to be resolved during run-time and they are bonded on compile time.

Benefits of final keyword in Java

Here are few benefits or advantage of using final keyword in Java:


1. Final keyword can be applied to member variable, local variable, method or class in Java.

2. Final member variable must be initialized at the time of declaration or inside constructor, failure to do so will result in compilation error.

3. You can not reassign value to final variable in Java.

4. Local final variable must be initializing during declaration. 

5. Only final variable is accessible inside anonymous class in Java.

6. Final method can not be overridden in Java.

7. Final class can not be inheritable in Java.

8. Final is different than finally keyword which is used on Exception handling in Java.

9. Final should not be confused with finalize() method which is declared in object class and called before an object is garbage collected by JVM.

10.All variable declared inside java interface are implicitly final.

11.Final and abstract are two opposite keyword and a final class can not be abstract in java.

12 Final methods are bonded during compile time also called static binding.

13.Final variables which is not initialized during declaration are called blank final variable and must be initialized on all constructor either explicitly or by calling this(). Failure to do so compiler will complain as "final variable (name) might not be initialized".

14. Making a class, method or variable final in Java helps to improve performance because JVM gets an opportunity to make assumption and optimization.

15. As per Java code convention final variables are treated as constant and written in all Caps

16.Final keyword improves performance. Not just JVM can cache final variable but also application can cache frequently use final variables.

17. Final variables are safe to share in multi-threading environment without additional synchronization overhead.

18. Final keyword allows JVM to optimized method, variable or class.

Final keyword declaration


 final int hoursInDay=24;



Program : FinalExample.java

public class FinalExample {

        public static void main(String[] args) {
             
                /*
                 * Final variables can be declared using final keyword.
                 * Once created and initialized, its value can not be changed.
                 */
                final int hoursInDay=24;
             
                //This statement will not compile. Value can't be changed.
                //hoursInDay=12;
             
                System.out.println("Hours in 5 days = " + hoursInDay * 5);
             
        }
}
Output 



G:\>javac FinalExample.java
G:\>java FinalExample
Hours in 5 days = 120


Example of Final variable, Final method and Class in Java

Abstract Class Example in Java Program

Java Abstract classes are used to declare common characteristics of subclasses. An abstract class cannot be instantiated. It can only be used as a super class for other classes that extend the abstract class. Abstract classes are declared with the abstract keyword. Abstract classes are used to provide a template or design for concrete subclasses down the inheritance tree.
Like any other class, an abstract class can contain fields that describe the characteristics and methods that describe the actions that a class can perform. An abstract class can include methods that contain no implementation. These are called abstract methods. The abstract method declaration must then end with a semicolon rather than a block. If a class has any abstract methods, whether declared or inherited, the entire class must be declared abstract. Abstract methods are used to provide a template for the classes that inherit the abstract methods.
Abstract classes cannot be instantiated; they must be subclassed, and actual implementations must be provided for the abstract methods. Any implementation specified can, of course, be overridden by additional subclasses. An object must have an implementation for all of its methods. You need to create a subclass that provides an implementation for the abstract method.
A class abstract Vehicle might be specified as abstract to represent the general abstraction of a vehicle, as creating instances of the class would not be meaningful.

You can require that certain methods be overridden by subclasses by specifying the abstract type modifier. These methods are sometimes referred to as subclasser responsibility because they have no implementation specified in the superclass. Thus, a subclass must override them—it cannot simply use the version defined in the superclass. To declare an abstract method, use this general form:

abstract type name(parameter-list);

 As you can see, no method body is present. Any class that contains one or more abstract methods must also be declared abstract. To declare a class abstract, you simply use the abstract keyword in front of the class keyword at the beginning of the class declaration. There can be no objects of an abstract class. That is, an abstract class cannot be directly instantiated with the new operator. Such objects would be useless, because an abstract class is not fully defined. Also, you cannot declare abstract constructors, or abstract static methods. Any subclass of an abstract class must either implement all of the abstract methods in the superclass, or be itself declared abstract. Here is a simple example of a class with an abstract method, followed by a class which implements that method:

Program AbstractDemo.java

abstract class Shape
{
 abstract void draw();
}
class Rectangle extends Shape
  {
   void draw()
    {
     System.out.println("Drawing Rectangle");
    }
  }

class Traingle extends Shape
  {
   void draw()
    {
     System.out.println("Drawing Traingle");
    }
  }

class AbstractDemo
 {
  public static void main(String args[])
   {
    Shape s1=new Rectangle();
    s1.draw();
    s1=new Traingle();
    s1.draw();
   }
 }
Output 


G:\>javac AbstractDemo.java
G:\>java AbstractDemo
Drawing Rectangle
Drawing Traingle 



Abstract Class Example in Java Program

The subclass must define an implementation for every abstract method of the abstract superclass, or the subclass itself will also be abstract. Similarly other shape objects can be created using the generic Shape Abstract class.
A big Disadvantage of using abstract classes is not able to use multiple inheritance. In the sense, when a class extends an abstract class, it can’t extend any other class.

Method Overriding in Java

In a class hierarchy, when a method in a subclass has the same name and type signature as a method in its super class, then the method in the subclass is said to override the method in the super class. When an overridden method is called from within a subclass, it will always refer to the version of that method defined by the subclass. The version of the method defined by the super class will be hidden.

Rules for method overriding:

  • The argument list should be exactly the same as that of the overridden method.
  • The return type should be the same or a subtype of the return type declared in the original overridden method in the super class.
  • The access level cannot be more restrictive than the overridden method's access level. For example: if the super class method is declared public then the overridding method in the sub class cannot be either private or public. However the access level can be less restrictive than the overridden method's access level.
  • Instance methods can be overridden only if they are inherited by the subclass.
  • A method declared final cannot be overridden.
  • A method declared static cannot be overridden but can be re-declared.
  • If a method cannot be inherited then it cannot be overridden.
  • A subclass within the same package as the instance's superclass can override any superclass method that is not declared private or final.
  • A subclass in a different package can only override the non-final methods declared public or protected.
  • An overriding method can throw any uncheck exceptions, regardless of whether the overridden method throws exceptions or not. However the overriding method should not throw checked exceptions that are new or broader than the ones declared by the overridden method. The overriding method can throw narrower or fewer exceptions than the overridden method.
  • Constructors cannot be overridden.

Program Override.java

class A
 {
  int i, j;
  A(int a, int b)
   {
    i = a;
    j = b;
   }
  void show()
   {
    System.out.println("i and j: " + i + " " + j);
   }
 }

// Create a subclass by extending class A.


class B extends A
 {
    int k;
    B(int a, int b, int c)
     {
      super(a, b);
      k = c;
     }
// overload show()

    void show(String msg)
     {
      System.out.println(msg + k);
     }
 }

class Override
 {
   public static void main(String args[])
    {
     B subOb = new B(10, 20, 30);
     subOb.show("This is k: ");

// this calls show() in B

     subOb.show();

// this calls show() in A
    }
}


Here, super.show( ) calls the superclass version of show( ). Method overriding occurs only when the names and the type signatures of the two methods are identical. If they are not, then the two methods are simply overloaded


Output 

G:\>javac Override.java
G:\>java Override
This is k: 3
i and j: 1 2

Method Overriding in Java


 

learn java programming Copyright © 2011-2012 | Powered by appsackel.org