Structure of Java Class:
Example:
public class FinalFieldsExample {
public final int a;
FinalFieldsExample(int val) {
a = val;
}
public void display()
{
System.out.println("The value of final field a is : " + a);
}
public static void main(String[] args) {
FinalFieldsExample t1 = new FinalFieldsExample(10);
t1.display();
FinalFieldsExample t2 = new FinalFieldsExample(20);
t2.display();
}
}
Quick list of the components of a class: (around 7 components)
■ The package statement
■ The import statement
■ Comments
■ Class declarations and definitions
■ Variables
■ Methods
■ Constructors
Package Statement:
All Java classes are part of a package. You can explicitly define a named package; otherwise, it become part of default package which doesn't have name.
- The package statement should be the first statement in a source code file for Java class definition.
- If the package statement after the class definition, the code won't compile.
- A package statement can't be within the class definition.
- A class cannot define multiple package statements. The code won't compile.
- Package statement must appear exactly once in a class.
Import statement
Typically to use a class or interface from another package, you must use its fully qualified name. Because this become tedious and can make your code difficult to read, you can use the import statement to use the simple name of a class or interface in your code.
- import statement follows the package statement but before the class definition.
- Reversing this order will result in your code failing to compile.
Comments
Can appear multiple times, and can use at multiple places. 2 types of comments:
a) multiline comments, b) end-of-line comments.
multiline comments: /* ..... */
end-of-line comments: // this is a comment
- Multiline comments can contain any special characters (including Unicode characters)
/*
Multi-line comments with
special characters &%^*{}|\|:;"'
?/>.<,!@#$%^&*()
*/
- The text between // and the end of line is treated as a comment.
- You can as well define end of line comment within a multiline comment.
Class Declaration
Simplest declaration: keyword class followed by the class name.
Class declaration is composed of the following parts:
- Access Modifiers
- Non access modifiers
- Class name
- Name of the base class, if the class is extending another class
- All implemented interfaces, if the class is implementing any interfaces
- Class body ( fields, constructors, methods) included within pair of curly braces { }
Compulsory Optional
Keyword class Access modifier, such as public
Name of the class Nonaccess modifier, such as final
Class body, marked by the opening Keyword extends together with the name
and closing curly braces, {} of the base class
Keyword implements together with the name
of the interfaces being implemented
Class Definition
A class is a design used to specify the properties and behavior of an object.
The properties of an object are implemented using variables.
The behavior is implemented using methods.
- A class name starts with keyword, class. The keyword is case sensitive, uses lower case letters only.
- The state of class is defined using attributes or instance variables.
- Each object has its own copy of instance variables. Instance variables are defined within a class but outside all methods in a class.
- The behavior is defined using methods.
- A class definition also includes comments and constructors.
Variables
Each object has its own copy of the instance variables.If you change the value of an instance variable for an object, the value for the same named instance variable won’t change for another object.
A single copy of a class variable or static variable is shared by all the objects of a
class.
Methods
Methods are generally used to manipulate instance variables.
A class method or static method is used to work with the static variables.
Constructors
A class constructor is used to create and initialize the objects of a class.
A class can define multiple constructors that accept different sets of method parameters.(Constructor overloading)
Definition of interfaces in java source code files:
An interface specifies a contract for the classes to implement.
It is a grouping of related methods and constants, but the methods in an interface cannot define any implementation.
- The definition of an interface starts with keyword, interface, all lowercase letters.
- An interface can define constants and methods.
- All variables in an instance are by default final static.
- All methods in an instance are public by default.
The classes and interfaces can be defined in any order of occurrence in a Java source code file.
Note:
- If you define a public class or interface in a file, its name should match the name of the Java source code file.
- A source code file can't define more than one public class or interface. If you try to do, your code won't compile.
- A java source code file can define multiple interfaces or classes in a single file.
Executable Java Classes
An executable Java class is a class which, when handed over to the JVM, starts its execution at a particular point in the class—the main method, defined in the class.
The JVM starts executing the code that is defined in the main method.
Typically, an application consists of a number of classes and interfaces that are defined in multiple Java source code files. Of all these files, a programmer designates one of the classes as an executable class.
The main method makes a Java class executable.
main() method signature:
The main method should comply with the following rules:
■ The method must be marked as a public method.
■ The method must be marked as a static method.
■ The name of the method must be main.
■ The return type of this method must be void.
■ The method must accept a method argument of a String array or a variable argument of type String.
public static void main(String[] args) {
....
}
It’s valid to define the method parameter passed to the main method as a variable argument (varargs) of type String:
public static void main(String... args)
public static void main(String args...) ---> X (wrong).The ellipses(...) should follow the data type.
public static void main(String[] arguments)
public static void main(String[] HelloWorld)
The names of the method arguments are arguments and HelloWorld, which is acceptable.
To define an array, the square brackets, [], can follow either the variable name or its type. The following is a correct method declaration of the main method:
public static void main(String[] args)
public static void main(String minnieMouse[])
The square brackets, [], can follow either the variable name or its type.
It’s interesting to note that the placement of the keywords public and static can be interchanged, which means that the following are both correct method declarations of the main method:
public static void main(String[] args)
static public void main(String[] args)
Java does not pass class name on command line as an argument to main method.
Java Packages
You can use packages to group together a related set of classes and interfaces.
Packages also provide access protection and namespace management.
You can create separate packages to define classes for separate projects.
Note: In real-life projects, you will never work with an unpackaged class or interface. Almost all organizations that develop software have strict package-naming rules, which are often documented.
Packaged classes are part of a named package—a namespace—and they’re defined as being part of a package by including a package statement in a class.
All classes and interfaces are packaged.
If you don’t include an explicit package statement in a class or an interface, it’s part of a default package.
A few of important rules about packages:
■ Per Java naming conventions, package names should all be in lowercase.
■ The package and subpackage names are separated using a dot (.).
■ Package names follow the rules defined for valid identifiers in Java.
■ For packaged classes and interfaces, the package statement is the first statement in a Java source file (a .java file). The exception is that comments can appear before or after a package statement.
■ There can be a maximum of one package statement per Java source code file (.java file).
■ All the classes and interfaces defined in a Java source code file will be defined in the same package. There is no way to package classes and interfaces defined within the same Java source code file in different packages.
Directory structure and package hierarchy:
The hierarchy of the packaged classes should match the hierarchy of the directories in which these classes and interfaces are defined in the code.
There isn’t any constraint on the location of the base directory in which the directory structure is defined.
Setting CLASSPATH for packaged classes
To enable the Java Runtime Environment (JRE) to find your classes, add the base directory that contains your packaged Java code to the classpath.
For the above example:
To enable the JRE to locate the class com.oracle.javacert.associate.ExamQuestion, add the directory C:\ProjectCode to the classpath.
Using import statement, no need to use the fully qualified name of class in different package.
Note:
The import statement doesn’t embed the contents of the imported class in your class, which means that importing more classes doesn’t increase the size of your own class. It lets you use the simple name for a class or interface defined in a separate package.
It’s important to note that you can’t use the import statement to access multiple classes or interfaces with the same names from different packages. For example, the Java API defines the class Date in two commonly used packages: java.util and java.sql. To define variables of these classes in a class, use their fully qualified names with the variable declaration:
class AnnualExam {
java.util.Date date1;
java.sql.Date date2;
}
Code to import classes with the same name from different packages won’t compile.
Ex:
import java.util.Date;
import java.sql.Date;
class AnnualExam { }
The above code won't compile.
You can import either a single member of all members(classes and interfaces) of a package using the import statement.
By using the wildcard character, an asterisk (*), you can import all of the public members, classes, and interfaces of a package.
Unlike in C or C++, importing a class doesn’t add to the size of a Java .class file. An import statement enables Java to refer to the imported classes without embedding their source code in the target .class file.
You can’t import classes from a subpackage by using an asterisk in the import statement.
You have to explicitly import subpackages.
If you don't explicitly package your classes or interface, they packaged in default package. This default package is automatically imported in Java classes and interfaces defined within the same directory on your system.
Note: A class from a default package can’t be used in any named packaged class, regardless of whether they are defined within the same directory or not.
Static imports:
You can import an individual static member of a class or all its static members by using the import static statement.
Ex: import static certification.ExamQuestion.*;
For final, it can be assigned different values at run-time when initialized. A final variable must either be assigned a value, or have a value assigned in its constructors.
Final(non-static) variables can differ from object to object!!! But that's only if the initialization is made within the constructor!
Example:
public class FinalFieldsExample {
public final int a;
FinalFieldsExample(int val) {
a = val;
}
public void display()
{
System.out.println("The value of final field a is : " + a);
}
public static void main(String[] args) {
FinalFieldsExample t1 = new FinalFieldsExample(10);
t1.display();
FinalFieldsExample t2 = new FinalFieldsExample(20);
t2.display();
}
}

No comments:
Post a Comment