Вы находитесь на странице: 1из 1

Blocks, Methods and Constructors in Java A block is a group of zero or more statements between balanced braces {} and can

be used anywhere a single statement is allowed like a method body, outside a me thod but inside the class atc. A method in Java can be considered as a block wit h a name. Variables declared inside a block has a scope or lifetime limited to t hat block. For example, if you declare a variable myVar inside a method, it won' t be recognized outside. However, a variable declared in one block will be avail able to its inner blocks. These variables are called local variables as they are local to a block. Local variables are always thread safe as a different copy of local variable will be created per thread. A local variable must be initialize d before you try to use it, else compiler will complain. Methods Methods are blocks of code with a name containining the executable code in Java. Methods can optionally accept data as parameters and also optionally return dat a. Executing a Java program means executing its methods. We will initially call one method and then that method can call another method and so on. When you exec ute a java class (using java command) in console, JVM calls a predefined method (the main method) of this class, this method can then call another method of the same class or different class and so on. public static void main(String[] args) { //method body } public - is the access specifier that tells how visible the method is within and outside the class. static - this is a static method, not an instance method. void - return type. void means nothing is returned. main - name of the method. args - A String array to accept command line arguments. Methods will always be contained within a class. The visibility of a method is c ontrolled by its access modifiers public, private, protected and default (no acc ess modifier). Methods may be either static or instance. Static methods can acc ess only static variables, but instance methods can access static as well as non -static methods. Static methods can be called using a class name as well as obje ct name, instance methods can be called only using an instance.Regardless of the type of method, there is only a single copy of a method. Each instance of the c lass (an object) uses the same definition of the method. Constructors Constructors can be considered as special methods with the same name of the clas s used to initialize an object. Whenever an object is created, a constructor is executed. A default constructor that has no arguments is provided automatically for all classes if there are no user defined constructors. If the developer prov ides at least one constructor, the compiler's default constructor is no longer a dded. It is always good have an explicit, default, no-argument constructor.

Вам также может понравиться