Java Program composed of classes and a class consists of methods and variables. I will give you an introduction to elements of Java program here.
1. Classes and Objects:
Objects are the core of Java Programs , Object may represent a real world problem which we are trying to found solution to .Object is an instance of a class .In Java Program you will write classes and when the program run , objects will be created and do the task .
The Java Class has two components: - Class declaration.
- Class Body.
The
Class declaration contains the class name and the access modifier .The access modifier defines the accessibility of the class. There are other properties you can set in the declaration like inheritance from other class (Using extend keyword), or the class can't be base for other classes (Using final keyword) or no objects can't be created from this class (Using abstract keyword).
The Class body comes after the class declaration and it is contained within braces. The class body contains functions and variables.
The process of creating an object from the class called "instantiation" .That is why objects are also called instances of classes. Objects can be books, cars, buildings etc .For a example all books are represented by class called book .Each object has status , for example book have a name , category and price , these characteristics are called properties. Each object has a behavior, for example "OpenBook", "CloseBook", these behaviors is called methods.
2. Methods: The methods contain the logic of the application, it do operation on the data. Each method has a declaration and body .The declaration includes the method name, return type, parameter, and accessibility. The body contains what method do, which determine the behavior of the object.
The method can be static this means, it can be invoke without referencing to an object. For example the main function of your application.
3. Variables:
Variables are the container of data. Object state is carried by variables. Variables have declaration which specifies variable name, type and accessibility. The variable must have legal identifier (name) and not a java keyword.
Rules of java legal identifier: - Start with [a-z][A-Z] , or _ or $ .Don't begin with digit.
- First character can by followed by any series of letters or digits.
- Must not be a keyword.
The declaration of variable :Should look like this: - Code:
<Type> <identifier>;
You can assign a value to the identifier: - Code:
<Type> <identifier> =<value>;
If your data type is a class, your declaration should be like this:
- Code:
<classname> <identifier>=new <classname>() ;