Block of code: Packages | Classes | Methods

Java: Block of Code:

Rupam Jha

--

Let us try and understand today what are the basic definitions we should be aware of in order to write a code template in Java. It is very essential to be clear in understanding the syntax of any language given to us. Syntax typically refers to a structured form of code that any computer could interpret. If a user tries to execute a command or say block of code without a proper syntax, it will end up generating syntax error, usually causing the program run to fail. In the most basic terminology I would refer a syntax to be the spelling and grammar of any programming language. Each language defines its own syntactical rules that controls which word could a computer interpret and what punctuation is necessary to be a correctly structured document.

There are three level of syntax which include:

Lexical syntax: they relate to all the basic symbols of any language[i.e. names, operators, etc.]

Concrete syntax: they relate to the context free grammar i.e. they consist of set of rules that define the way the program looks to the programmer.[i.e. expressions, statements, etc.]

Abstract syntax: they relate to the set of trees used to represent programs in implementation i.e. it defines the way program looks to the compiler.

The relation between the abstract and concrete syntax is accomplished by program called reader. The reader takes a piece of text that is expected to suffice the set of rules of the concrete syntax, and if the rules aren't accomplished error is generated. Otherwise, the reader transforms the text meeting the concrete syntax into the tree, meeting the definition of abstract syntax. This tree gives representation to the structure of program.

Hello Comrades,

As the few lines mentioned above gave you a glimpse of what are we going to understand today, I would further brief you on todays article. We today will deeply understand what are packages, classes[along with objects] , methods in Java. So to begin with, let us dive into packages first.

Packages:

The most innovative feature of Java is a package. Encapsulating of group of classes, interfaces, annotations, is termed as Packages in Java. It basically is a mechanism of grouping up similar type of classes, interfaces based on functionalities. Java gives an enormous set of packages to help avoid code redundancy(rewriting of any complex code).

Benefits Packages provide are of re-usability, avoiding name conflicts, obtaining controlled access, data encapsulation and easy maintenance of code.

  • Re-usability:

It is a mechanism that facilitates to reuse fields or methods of any existing class, when we create any new class. Association and Inheritance are the ways to achieve code re-usability. Association refers to (HAS-A) relationship: i) composition(strong) ii)aggregation(weak), where as Inheritance refers to (IS-A) relationship. Without forming a relation, re-usability is not achievable.

To explain the mentioned above point with a real life example: We know, Car is a vehicle and bike is a vehicle, when we have this IS-A relationship, always prefer inheritance. If a relationship is HAS-A then go for association. Car has an engine and car has a music player. But as we know, if we remove the engine from car, car turns out to be useless, but that is not the case with music player. Hence, relation of car : engine is that of a composition(strong coupling) and car : music player is that of aggregation(weak coupling).

Association is relation between two separate classes which establishes through their Objects. Association can be one-to-one, one-to many, many-to-one, many-to-many.

taking a look at code template:

In coding, we create constructors for strong association and methods for weak association.

if we perform such coding then, class A has a relationship with class B. Association is nothing but creating an object of a class in another class as described above.

Inheritance simply defines itself as child class inheriting property (data members) and functionalities (methods) from parent class. Inheritance is simply a process of defining a new class based on an existing class by extending the common properties and functionalities.

eg: Inheritance in Java

The derived classes(child classes) can inherit all the members and methods that are declared as public or protected in the parent class. If the members or methods are declared as private then derived class cannot access it directly, they will need public getter and setters.

Avoiding name conflicts:

Packages in a way help us to uniquely identify a class. Conceptually consider a package to be equivalent to folders in our system, as we can have same filenames in different folders similarly we can have same class names into different packages in Java, as the class names are qualified with the package names. They make searching, locating and usage of classes, interfaces easier.

eg:
If there is a class name Employee in two packages : sales and marketing then the package name would be as follows:
com.sales.Employee
com.marketing.Employee
  • Controlled access:

Packages offers us access protection such as protected classes, default classes and private classes. As mentioned in above lines, a subclass cannot have an access modifier which are less accessible than the parent class. Also methods or data members that are private cannot be inherited.

eg: if a super class(parent class) has any method or variable declared as public then the sub class (child class) will have access modifier as public only. But if the super class has any variable or method declared as Protected then it can be of access modifier protected or public in sub class.

Data encapsulation:

Encapsulating data means one class must not hold an access to the private members of the other class. The main advantage it provides is : security of a data.

The term encapsulation and data hiding are not similar. In encapsulation data can be public or private, but in data hiding it is mandatory to have data only as private.

  • Easy maintenance of code:

Using packages we can organize our project better and can easily locate related classes.

Packages are further classified into two types : pre-defined and user-defined packages. Built-in packages or say pre-defined packages are those that come along the JDK to simplify our task as a programmer. They have predefined classes and interfaces that are part of Java APIs. User defined packages are those which are developed by users in order to put together group of related classes, interfaces or sub-packages.

If we don't mention any package statement the class names are put into the default package, which holds no name. It is recommended not to define a class without any package.

A class can have only one package statement but it can have more than one import package statement.

Classes[and objects]:

Java being an object oriented language has it heart as Objects and Classes. A class describes the contents of an object that belongs to it. It basically describes an aggregate of data fields(termed as instance variables) and defines operations(termed as methods). Where as an object is an element(refer as instance)of a class. Objects holds behavior of any class. While objects are the actual components of a program, the class specifies how objects (instances) are created and how they behave.

An object is an instance of class. A class has members. Members can be fields, methods or constructors. Class can also contain initializers(instance/ static). Static initializers run only once when the class is loaded, but an instance initializer will run every time an instance(object) is created.

We can simply define a class as a user defined prototype from which objects are created. Its general declarations can include components like modifiers, class keyword, class name, superclass(if any), interfaces(if any), body, constructors, fields and methods.

A class can have access modifier as public or default(when class has no access specifier). We cannot declare class as protected or private. But a nested class(class within a class) can have all the access specifiers. If a class has no modifier (default) it can be accessible only within its own package. If it has access modifier as public, it is accessible where ever its package is. If a class is using abstract as modifier, we cannot instantiate that class(cannot create object of that class). A class using final as a modifier cannot be extended by any other class. Making a class static assigns an inner declared class as a top- level class.

The class keyword helps us create class; followed by a class name(should begin with initial letters). Also if the class has to extend or implement any class or interfaces we can use keywords like extends or implements to call the super class or interface.

The body of a class is surrounded in curly braces{}. Constructors, as we know are used for initializing new objects. A variable (fields) provides the state of the class and its object, where as methods are used to implement the behavior of a class and its objects.

Constructors are not same as methods. Where a method operates on existing objects , a constructor brings a new object to existence. Constructors always are invoked with operator new.

Every class in Java is implicitly a sub class of a predefined class called Object. As mentioned that every class by default extends Object class, so there are few built in behavior that is present in every class [will discuss in brirf about Object class in upcoming article].

Java supports six types of classes namely:

POJO classes:

POJO stands for Plain Old Java Object. It is a class that contains only private variables and setters and getters methods to use those variables. It may not have a no-argument constructor. It holds no implementation to pre-specified interfaces and should not contain pre-defined annotations.

Static classes:

The keyword static typically describes how objects gets managed within a memory. A static object always belongs to the class rather than belonging to the object of the class. A static class can contain only static members and we cannot create any object of the static class directly.

eg: STATIC class

Concrete classes:

Any Java class having implementation to all its methods are termed as concrete classes. They cannot hold any method without an implementation of it. This class can be instantiated.

CONCRETE class example

Abstract classes:

Any class declared using abstract keyword and holding zero or more abstract methods (methods without any implementation written in them) are termed as an abstract class. These classes can have constructors and static and final methods as well.

ABSTRACT class example

Final classes:

Final keyword when used along the class makes the class that cannot be extended by any other classes. Thus making a class immutable. We can achieve class immutability by making the class final, by declaring the variables as private , by not providing any setters, by initializing all the fields via constructors performing deep copy[ we will cover this cloning topic later] and by making all the mutable fields as final so that its value can be assigned only once.

Inner classes [*Nested Inner class |*Method Local Inner class | *Anonymous Inner class | *Static Nested class ]

Inner class in Java is used to enhance encapsulation . An inner class is enclosed within a class.

The nested Inner class has access to all the private member variables of an outer class. These nested inner classes can have access modifiers.

The method Local Inner class is declared inside an outer class method.

Anonymous Inner class is declared inside the outer class and holds no name .

Just like a class has static member variables, similarly a class can have static class as its member.

flow of calls to methods explained in Java class

Methods:

Method is an action that an object is able to perform. A method is block of code which runs only when we call it. Only a main()method is the method that doesn’t require any explicit call. Methods, in Java are also termed as Functions. Java has two types of methods: user-defined and pre-defined.

declaring a method:accessModifier returnType methodname(parameters){
//statements
}
eg: public static int addNumbers(int a, int b){
int c = a+b;
return c;
}
/**
* public = access modifier
* static = to weather method can be accessed without object or not
* int = the return type(if return type is void, method will not return anything)
*/

A method when declared as final cannot be overridden. An abstract method has no body( no definition/ implementation written inside it), any subclass of it will provide definition to the abstract method. A synchronized method will require a locking before any execution[shall discuss in Multi threading]. A native method is a method whose implementation is not written in Java, but in some [platform dependent way and a static method doesn't apply to any particular instances(object).

Hope this article was beneficial to your knowledge.

That is it on this article from my end. For any queries or suggestions to modify this article or any requests topics you can reach me here.

Until next time…

Peace Out!

Rupam Pawan Jha

--

--