Java Constructors, Packages and Import Statement

Java Constructors

public class Employee {


public Employee () {


}

}

................................................................................

Employee emp = new Employee () ;
................................................................................


  • A constructor is used to create an instance of a class.
  • Constructors can take parameters.
  • A constructor that take no argument is called  a no-arg constructor.

A constructor is used to create an object. In the Java programming language, constructor are declared with the same name as their class used to create an instance of an object.
Constructor are invoked  using the new keyword.


package Statement


The package keyword is used in Java to group classes together. A package is implemented as a folder and, like a folder, provides a namespace to a class.




Packages

In Java , a package is a group of (class) types. There can be only one package declaration for a file.
Packages are more than just a convenience. Packages create a namespace, a logical collection of things, like a directory hierarchy.

It is a good practice to always use a package declaration. The package declaration is always at the top of the file. 


Imports

You could refer to a class using its full qualified namespace in your applications , as shown in the following example:

java.util.Date date = new  java.util.Date();

But that would quickly leads to a lots of typing!Insteads, Java provides the import statement to allow you to declare that you want to reference a class in another package.

Note: It is a good practice to use the specific, fully qualified package and class name to avoid confusion when there are two classes with the same name , as in the following example :
java.sql.Date and java.util.Date. The first is the Date class used to store a Date type in a database, and java.util.Date is a general purpose Date class. As it turns out, java.sql.Date is a subclass of java.util.Date.


import Statement

The import keyword is used to identify classes you want to reference in your class.

  • The import statement provides a convenient way to identify classes that you want to reference in your class.
          import java.util.Date;
  • You can import a single class or an entire package.
          import java.util.*;
  • You can include multiple import statements:
         import java.util.Date;
         import java.util.Calendar;
  • It is good practice to use the full package and class name rather than the wildcard *to avoid class name conflicts.
More on import


  • Import statements follow the package declaration and precedes the class.
  • An import statement is not required.
  • By default, your class always imports java.lang*.
  • You do not need to import classes that are in the same package






About Codingwelove

Codingwelove
Recommended Posts × +

0 comments:

Post a Comment