Java/Packages Classes and Interfaces

From Meshplex

Jump to: navigation, search
Image:Java_programming.jpg
Introduction to Java
Overview of Java
How to Setup Java on your PC
Java Data Types, Variables,and Arrays
Operators
Java Packages, Classes, and Interfaces
Java Program
Java Modifiers
Java Control Statements
Java Exception Handling
Java Object Oriented Programming
Java Wrappers
Java Strings
Java Math
Java Arrays
Java Random Numbers
Java Date and Time
Java Regular Expressions
Java Java Collections
Java Generics
Java Thread and Multithreading
Java IO and file Handling
Java Network Programming
Java RMI
Java Image, Audio, Video
Java GUI
Java Applets
Java Internationalization
Java JDBC
Java and XML

Contents

[edit] Intro

In all the examples which we have taken to make you understand the concepts of the various features of java we have everywhere defined the class from the same name space and it means that very time we had to give a unique name to each and every class to avoid the confusions. But this is not a very convenient practise to be followed and thus Java provides us with a concept of “package”.


We can define the classes inside a package which are accessed only by the code present in that package and hence any outside interference is strictly restricted within the package. Not only this as per your choice you can also define class members which will be accessible to other members of the same package too.

It is quite easy to define a package by using the command “package”. In the first line of any Java file or program. And any classes defined within this package will belong to that above mentioned package only.

General syntax of defining package in any java file:

package name;

Where package = key word or command

name = name given to the package

Example:

package mynewpackage;

Now all the .class files used in this package will be stored in the directory which is been created for mynewpackage package.

Packages act as containers for the various classes which are being used in that particular package and the classes act as containers for the data and the code written in that java files which are kept in the package container so we can sum up the above written statement as class is a storehouse for the data and the code and the package acts as a storehouse for the classes.

The class is basically the smallest unit of abstraction .Java provides four categories of visibility for the class members:

■ Subclasses in the same package

■ Non-subclasses in the same package

■ Subclasses in different packages

■ Classes that are neither in the same package nor subclasses

Along with this Java provides us with other three access specifiers, private, public, and protected, which provides us a variety of ways to produce the many levels of access required by these categories.

Although the access control mechanism provide by Java may look bit complicated, we can mention it in the summary form to make you understand it in a simple way:

1. Anything declared public can be accessed from anywhere.


public void display() {
 System.out.println("Publically available to all the classes in all the packages.");
}

2. Anything declared private cannot be seen outside of its class.


private void display() {
 System.out.println("Privately available to only class in which it is declared.");
}

3. When a member does not have an explicit access specification, it is visible to subclasses as well as to other classes in the same package. This is the default access. No need to mention anything in the access modifier section.


void display() {
 System.out.println("Available only within the package.");
}

4. If you want to allow an element to be seen outside your current package, but only to classes that subclass your class directly, then declare that element protected.


protected void display() {
 System.out.println("Available only with the package and subclasses" +  
                     " declared in the other packages.");
}

Packages provide us with a very efficient mechanism for making various compartments for various different classes and can keep them separate from each other and all the standard classes provided in Java are stored in some named package. Since we now properly understand that all the package names must always be in synchronisation with the classes stored in those packages to avoid collision and confusion but it may lead to hectic work by giving long dot separated package names and then using them everywhere when required.

To make this again simple and easier for the Java programmers, Java has given the mechanism of importing the packages. We can include the import statement to bring certain classes or the entire package into visibility. We can directly refer to the class by just writing its name if we have imported the package once.


In a Java source file, an import statement is mentioned exactly next to the package statement in the Java file, before any class definition.

General syntax for import is:

import package name 1.[package name 2].(classname|*);

Where import = keyword or command package name 1= name of top-level first package to be imported package name 2= name of subordinate package inside the outer package Class name/*= name of classes to be imported from the particular package/all the class files if * is mentioned from the package.

It is recommend to define the class file names instead of mentioning * which means that you want to import all the files as it may increase the import time a lot as there are chances of having many big files in the package but it doesn’t effect the run time performance of the classes.

Java includes all its Java classes in a particular package termed as “Java”. The basic language functions are stored in a package inside of the java package called java.lang.

If by chance we have the class with similar name in two packages which we are trying to import it will be done and we will not find any error at the time of importing the class files from the packages but we will get a compile-time error and then will have to explicitly name the class specifying its package.

[edit] Java Classes

Although we have covered the concept of classes and objects in brief in our section Object oriented programming (OOPs), let’s take each one of them in detail as they are form the basic core in the working on Java programming too.

A class can be defined as a template which is used to create the objects or the instances of the same class. The properties owned by the objects or the instances will be exactly the same as the class of which they are the instance or object of.

A class is declared by the use of keyword “class” ( lowercase ). The normal structure of the class will have “variables”, followed by the “methods” which carry the code for those variables. Both the variables and the methods are called the “members” of the class.

Now we will try to analyze what we have understood by just going through a very basic example for a Class.

class Bed {
    double width;
    double height;
    double depth;
  }

As we have mentioned above in this section, a class defines a new type of data. In this case, the new data type is called Bed. We will use this name to declare objects of type Bed. Since the class creates only the instance and it doesn’t create an actual object. Thus, The preceding code does not cause any objects of type Bed to come into existence.

To actually create a Bed object, we will have to write a statement like the following:

Bed mybed = new Bed();

This statement will create an object mybed with all characteristics of class Bed like width, height and depth and it will have physical reality.

Nested and Inner Classes It is possible to define a class within another class; such classes are known as “nested” classes. The scope of a nested class is always limited by the scope of its enclosing class.

Therefore, if class B is defined within class A, then B is known to A, but not outside of A. A nested class has access to the members, including private members, of the class in which it is nested. However, the enclosing class does not have access to the members of the nested class.

There are two types of nested classes: static and non-static. A static nested class is one which has the static modifier applied. They are almost identical to non-nested classes except for scope details (they can refer to static variables and methods of the enclosing class without qualifying the name; other classes that are not one of its enclosing classes have to qualify its name with its enclosing class's name). That is, it cannot refer to members of its enclosing class directly.

The most important type of nested class is the inner class. An inner class is a Non-static nested class. It has access to all of the variables and methods of its outer class and may refer to them directly in the same way that other non-static members of the outer class do. Thus, an inner class is fully within the scope of its enclosing class.

How to declare objects: As we have understood till now that whenever we create a class we basically create a new data type and then we use it to have objects of that type. This is done in basically two steps first to declare a variable of that type and then create another copy of that class which will contain the physical values with respect to that type and assign it to that object. In Java all the objects are dynamically allocated with a keyword “new”

Bed mybed = new bed ( );

[edit] Java Methods

As it was mentioned in the head classes that class basically consist of two segments variable and methods. Methods consist of the functionality which has to be operated on the variables defined in the class.

General form of Methods is:

Type name (parameter list) {

// body of method

}

Where type=type of data returned by method, parameter list= list of types and identifier pairs separated by commas, basically the variables that receive the values used in the method,

Example:

int double (int i) {

return i * i;

}

Now, method double ( ) will return the square of whatever value it is called with. It means that double method has become a general-purpose method that will calculate the square root of any integer passed in it.

[edit] Java this Pointer

this pointer is one of the very interesting and confusing topic which you need to understand. this pointer is used in most of applications and believe me it is really worth undertanding. this pointer basically points to the self reference or we can say the current reference which is active at any time during the execution of the program. this pointer is associated with the object at the instance level and not at the class level. That means this pointer cannot be used in a static block or static method. this pointer is used to differentiate between the self object and the other object.

Take us take a smalll example.

We can say that there is a class called HumanBeing and me and you are two objects of this class. My eyes are brown and yours are blue. Now the I want to check the color of our eyes and if it is different then I would like to display a message "Eyes are different". I would say programmitically that if my eyes' color equal to your eyes' color then display message. Here eyes would be the attribute in both the objects and my is the this pointer.

public class ThisPointerExample {
 
  public static void main(String[] args) {
    HumanBeing me = new HumanBeing("Brown");
    HumanBeing your = new HumanBeing("Blue");
 
    System.out.println(me.isEqual(your));
  }
}
 
class HumanBeing {
 
  private String eyeColor;
 
  public HumanBeing(String color) {
    this.eyeColor = color;
 
  }
 
  public String getEyeColor() {
    return eyeColor;
  }
 
  public boolean isEqual(HumanBeing your) {
    return this.eyeColor.equals(your.getEyeColor());
  }
}

[edit] Java Interfaces

Interface helps us to specify what a class must do, but not the method or the steps to perform what is required to be done. Interfaces don’t have instance variables and their methods are defined without any body. We can implement these instances in any number of classes and one class can have multiple interfaces to be implemented.

This is made possible with the key word “interface”. Each class must create the complete set of methods which have been defined by the interface.

In the other programming languages normally, in order for a method to be called from one class to another, both classes should be available at compile time so the compiler can check to ensure that the method signatures are compatible. This requirement by itself makes for a static and nonextensible classing environment but in this type of system functionality gets pushed up higher and higher in the class hierarchy so that the mechanisms will be available to more and more subclasses. Interfaces are designed to avoid this problem. They disconnect the definition of a method or set of methods from the inheritance hierarchy. Since interfaces are in a different hierarchy from classes, it is possible for classes that are unrelated in terms of the class hierarchy to implement the same interface. This feature of Interface makes it acceptable to the users as it increases their efficiency and make it very compatible.

It is defined with the key word “interface”. The general syntax for defining an interface in any Java application is :

access interface name {

return-type method-name1(parameter-list);

type final-varname1 = value;

// ...

return-type method-nameN(parameter-list);

type final-varnameN = value; }

where access can be public or can be avoided to be written making it default package.

interface is the keyword defined to create an interface name specifies the name of interface

public interface Vehicle {

  public void changeGear(int gearNumber, boolean isFootGear);
}

[edit] Java Overloading

It is very much possible in java to have two or more methods of the same name within one class. They are completely independent of each other. An overloaded method is defined by changing the number of parameters, or their types, called in a method. This is called “Method Overloading” in java.

These methods must vary in their types or their parameters or both.

// An Example, taken from a program, of method overloading.
   public void setRoom(int a, boolean b, int c)
   {
       this.beds = (a>0) ? a : this.beds;
       this.smoking = b;
       test = c>0 ? c : test;
   }
   public void setRoom(int a, boolean b, int c, boolean d)
   {
       setRoom( a, b, c);
       if (d == true)
           printRoom();
   }

Previous Next