Login

Username:

Password: 

Join us Now |  Forgot Password? | Forgot UserName?

Java

Learn step by step



Class vs. Object

  • A class is a template or blueprint for how to build an object.

    • A class is a prototype that defines state placeholders and behavior common to all objects of its kind.
    • Each object is a member of a single class there is no multiple inheritance in Java.
  • An object is an instance of a particular class.

    • There are typically many object instances for any one given class (or type).
    • Each object of a given class has the same built-in behavior but possibly a different state (data).
    • Objects are instantiated (created).

Introduction to Java Classes

A class is nothing but a blueprint or a template for creating different objects which defines its properties and behaviors. Java class objects exhibit the properties and behaviors defined by its class. A class can contain fields and methods to describe the behavior of an object.

Methods are nothing but members of a class that provide a service for an object or perform some business logic. Java fields and member functions names are case sensitive. Current states of a class’s corresponding object are stored in the object’s instance variables. Methods define the operations that can be performed in java programming.

A class has the following general syntax 1:

<class modifiers>class<class name>
<extends clause> <implements clause>{

// Dealing with Classes (Class body)
<field declarations (Static and Non-Static)>
<method declarations (Static and Non-Static)>
<Inner class declarations>
<nested interface declarations>
<constructor declarations>
<Static initializer blocks>
}

A class has the following general syntax 2:

[modifiers] class ClassName {
(field definitions, constructors, and methods go here)
}


Below is an example showing the Objects and Classes of the Cube class that defines 3 fields namely length, breadth and height. Also the class contains a member function getVolume().


public class Cube {

int length;
int breadth;
int height;
public int getVolume() {
return (length * breadth * height);
}
}
How do you reference a data member/function?

This is accomplished by stating the name of the object reference, followed by a period (dot), followed by the name of the member inside the object.
( objectReference.member ). You call a method for an object by naming the object followed by a period (dot), followed by the name of the method and its argument list, like this: objectName.methodName(arg1, arg2, arg3).

For example:
cubeObject.length = 4;
cubeObject.breadth = 4;
cubeObject.height = 4;
cubeObject.getvolume()

Class Variables – Static Fields

We use class variables also know as Static fields when we want to share characteristics across all objects within a class. When you declare a field to be static, only a single instance of the associated variable is created common to all the objects of that class. Hence when one object changes the value of a class variable, it affects all objects of the class. We can access a class variable by using the name of the class, and not necessarily using a reference to an individual object within the class. Static variables can be accessed even though no objects of that class exist. It is declared using static keyword.

Class Methods – Static Methods

Class methods, similar to Class variables can be invoked without having an instance of the class. Class methods are often used to provide global functions for Java programs. For example, methods in the java.lang.Math package are class methods. You cannot call non-static methods from inside a static method.

Instance Variables

Instance variables stores the state of the object. Each class would have its own copy of the variable. Every object has a state that is determined by the values stored in the object. An object is said to have changed its state when one or more data values stored in the object have been modified. When an object responds to a message, it will usually perform an action, change its state etc. An object that has the ability to store values is often said to have persistence.

Consider this simple Java program showing the use of static fields and static methods


/ Class and Object initialization showing the Object Oriented concepts in Java
class Cube {

int length = 10;
int breadth = 10;
int height = 10;
public static int numOfCubes = 0; // static variable
public static int getNoOfCubes() { //static method
return numOfCubes;
}
public Cube() {
numOfCubes++; //
}
}

public class CubeStaticTest {

public static void main(String args[]) {
System.out.println("Number of Cube objects = " + Cube.numOfCubes);
System.out.println("Number of Cube objects = "
+ Cube.getNoOfCubes());
}
}

Output

Number of Cube objects = 0
Number of Cube objects = 0
Final Variable, Methods and Classes

In Java we can mark fields, methods and classes as final. Once marked as final, these items cannot be changed.

Variables defined in an interface are implicitly final. You can’t change value of a final variable (is a constant). A final class can’t be extended i.e., final class may not be subclassed. This is done for security reasons with basic classes like String and Integer. It also allows the compiler to make some optimizations, and makes thread safety a little easier to achieve. A final method can’t be overridden when its class is inherited. Any attempt to override or hide a final method will result in a compiler error.

Introduction to Java Objects

A typical Java program creates many objects, which as you know, interact by invoking methods. Through these object interactions, a program can carry out various tasks, such as implementing a GUI, running an animation, or sending and receiving information over a network. Once an object has completed the work for which it was created, its resources are recycled for use by other objects.

In general, the concept of an object is: a collection of data along with the functions to work with that data

  • as opposed to purely procedural languages where the data and functions are separate, and the data is passed to the function to work with

In Java, all code must be written inside object definitions

  • a class is an object definition, containing the data and function elements necessary to create an object
  • an instance of an object is one object created from the class definition (the process is known as instantiation)
  • the data and function elements are known as members
  • data members are also known as fields, properties, or attributes, and function members as methods

Here's a small program, called CreateObjectDemo, that creates three objects: one Point object and two Rectangle objects. You will need all three source files to compile this program.


public class CreateObjectDemo {

public static void main(String[] args) {

// Declare and create a point object and two rectangle objects.
Point originOne = new Point(23, 94);
Rectangle rectOne = new Rectangle(originOne, 100, 200);
Rectangle rectTwo = new Rectangle(50, 100);

// display rectOne's width, height, and area
System.out.println("Width of rectOne: " + rectOne.width);
System.out.println("Height of rectOne: " + rectOne.height);
System.out.println("Area of rectOne: " + rectOne.getArea());

// set rectTwo's position
rectTwo.origin = originOne;

// display rectTwo's position
System.out.println("X Position of rectTwo: " + rectTwo.origin.x);
System.out.println("Y Position of rectTwo: " + rectTwo.origin.y);

// move rectTwo and display its new position
rectTwo.move(40, 72);
System.out.println("X Position of rectTwo: " + rectTwo.origin.x);
System.out.println("Y Position of rectTwo: " + rectTwo.origin.y);
}
}

Output

Width of rectOne: 100
Height of rectOne: 200
Area of rectOne: 20000
X Position of rectTwo: 23
Y Position of rectTwo: 94
X Position of rectTwo: 40
Y Position of rectTwo: 72

The following three sections use the above example to describe the life cycle of an object within a program. From them, you will learn how to write code that creates and uses objects in your own programs. You will also learn how the system cleans up after an object when its life has ended.

Introduction to nested classes in Java

Overview

This article is going to shed some lights on the concepts of the implementation of the nested classes in Java in a simple and easy to comprehend manner. The various types of nested classes are explained with some examples that explain their usage and advantage over normal top-level-classes.

Concepts

One of the nice and highly advantageous features of Java is the ability to define nested classes, i.e. classes within classes. In java classes are either top-level-classes (classed defined directly within a package) or nested classes (classes defined within top-level-classes). One might wonder in regard to why all this complication is even helpful, and whether or not such classes bring any advantage to the java programmers at all.

Well, during the time I’ve spent exploring the what’s ad why’s of Java’s nested classes, I’ve realized two important, but distinct, advantages to that, and these are:

  • Having the ability to define nested classes will help grouping the related functionality together, imagine the case in which a certain class is being used only once from within another class, then there is no obvious need to add a clutter to the enclosing package by defining a top-level-class that will merely be used by only one another class. Thus, having that functionality contained within a a nested class increase readability and reduce clutter.
  • Another very important advantage of having nested classes is the fact that nested classes will be able to access all the class members of their enclosing top-level-class (including the private member methods and variables), this is a more efficient way than the traditional way of accessing the non-private members using an object instance and a noticeable advantage of this feature can be seen when developing event-based applications where action and event listeners can be defined as nested classes rather than having them as separate individual top-level-classes
  • A difference or may be an advantage nested classes posses over subclasses (as one might think, why not simply define subclasses instead of nested classes) is that subclasses can’t access private members (unless they are declared as protected) while nested classes can.

A class within another class is known as Nested class. The scope of the nested is bounded by the scope of its enclosing class

Nested Class

Fig1. Nested Class.

Static Nested Class

A satic nested class is the one that has static modifier applied. Because it is static it cannot refer to non-static members of its enclosing class directly. Because of this restriction static nested class is seldom used.

Non-static Nested class

Non-static Nested class is most important type of nested class. It is also known as Inner class. It has access to all variables and methods of Outer class and may refer to them directly. But the reverse is not true, that is, Outer class cannot directly access members of Inner class.

One more important thing to notice about an Inner class is that it can be created only within the scope of Outer class. Java compiler generates an error if any code outside Outer class attempts to instantiate Inner class.

Nested Class

Fig1. Non-Static Nested Class.


class Outer
{
public void display()
{
Inner in=new Inner();
in.show();
}

class Inner
{
public void show()
{
System.out.println("Inside inner");
}
}
}

class Test
{
public static void main(String[] args)
{
Outer ot=new Outer();
ot.display();
}
}

The output from this program is:

Inside inner


Related Videos