***Welcome to ashrafedu.blogspot.com ***This website is maintained by ASHRAF***

posts

Inheritance in Java

Inheritance is an important concept of OOP(Object-Oriented Programming). It is the mechanism by which one class is allowed to inherit the features(fields and methods) of another class.

Inheritance represents the IS-A relationship which is also known as a parent-child relationship.

Inheritance is used for code reusability.

The keyword used for inheritance is extends. The extends keyword indicates that you are making a new class that derives from an existing class. 

syntax:

class Subclass-name extends Superclass-name  

{  

   //methods and fields  

}  

In the terminology of Java, a class which is inherited is called a parent or superclass, and the new class is called child or subclass.

Types of Inheritance in Java

On the basis of class, there can be three types of inheritance in java: single, multilevel and hierarchical.

1. Single Inheritance: In single inheritance, subclasses inherit the features of one superclass.

In the image below , class A serves as a base class for the derived class B.


// Java program to illustrate the concept of single inheritance

import java.io.*;

import java.lang.*;

import java.util.*;

class one {

            public void print_one()

            {

                        System.out.println("one");

            }

}

class two extends one {

            public void print_two() { System.out.println("two"); }

}

// Driver class

public class Main {

            public static void main(String[] args)

            {

                        two g = new two();

                        g.print_one();

                        g.print_two();

            }

}

2. Multilevel Inheritance: In Multilevel Inheritance, a derived class will be inheriting a base class and as well as the derived class also act as the base class to other class. In the below image, class A serves as a base class for the derived class B, which in turn serves as a base class for the derived class C.


// Java program to illustrate the concept of Multilevel inheritance

import java.io.*;

import java.lang.*;

import java.util.*;

class one {

            public void print_one()

            {

                        System.out.println("one");

            }

}

class two extends one {

            public void print_two() { System.out.println("two"); }

}

class three extends two {

            public void print_three()

            {

                        System.out.println("three");

            }

}

public class Main {

            public static void main(String[] args)

            {

                        three g = new three();

                        g.print_one();

                        g.print_two();

                        g.print_three();

            }

}

3. Hierarchical Inheritance: In Hierarchical Inheritance, one class serves as a superclass (base class) for more than one subclass. In the below image, class A serves as a base class for the derived class B, C and D.

// Java program to illustrate the concept of Hierarchical inheritance

class A {

            public void print_A() { System.out.println("Class A"); }

}

class B extends A {

            public void print_B() { System.out.println("Class B"); }

}

class C extends A {

            public void print_C() { System.out.println("Class C"); }

}

public class Test {

            public static void main(String[] args)

            {

                        B obj_B = new B();

                        obj_B.print_A();

                        obj_B.print_B();

                        C obj_C = new C();

                        obj_C.print_A();

                        obj_C.print_C();

            }

}

Multiple inheritance

To reduce the complexity and simplify the language, multiple inheritance is not supported in java.

In Multiple inheritance, one class can have more than one superclass and inherit features from all parent classes. In java programming, multiple and hybrid inheritance is supported through interface only. 

// Java program to illustrate the

// concept of Multiple inheritance

import java.io.*;

import java.lang.*;

import java.util.*;

interface one {

            public void print_g();

}

interface two {

            public void print_for();

}

interface three extends one, two {

            public void print_g();

}

class child implements three {

            public void print_g()

            {

                        System.out.println("multiple");

            }

 

            public void print_in() { System.out.println("inheritance"); }

}

public class Main {

            public static void main(String[] args)

            {

                        child c = new child();

                        c.print_g();

                        c.print_in();

                        }

}




Nested Classes

The Java programming language allows you to define a class within another class. Such a class is called a nested class and is illustrated here:

class OuterClass {

    ...

    class NestedClass {

        ...

    }

}

 There are three advantages of inner classes in Java. They are as follows:

  1. Nested classes represent a particular type of relationship that is it can access all the members (data members and methods) of the outer class, including private.
  2. Nested classes are used to develop more readable and maintainable code because it logically group classes and interfaces in one place only.
  3. Code Optimization: It requires less code to write.

There are two types of nested classes non-static and static nested classes. The non-static nested classes are also known as inner classes.

  • Non-static nested class (inner class)
    1. Member inner class: A class created within class and outside method.
    2. Anonymous inner class: A class created for implementing an interface or extending class. The java compiler decides its name.
    3. Local inner class: A class was created within the method.
  • Static nested class : A static class created within the class.

Command-Line Arguments

A Java application can accept any number of arguments from the command line. The java command-line argument is an argument i.e. passed at the time of running the java program. The arguments passed from the console can be received in the java program and it can be used as an input.

Example:

class CommandLineEx{  

public static void main(String args[]){  

System.out.println("First argument is: "+args[0]);  

}  

}  

To run this java program, at least one argument must be passes from the command prompt.

javac CommandLineEx.java    //compiling

java CommandLineEx hai   //run

Example program to print multiple parameters:

class A{  

public static void main(String args[]){    

for(int i=0;i<args.length;i++)  

System.out.println(args[i]);   

}  

}  

javac A.java  

java A Ashraf  Msc Mtech

Java Arrays

An array is a collection of similar type of elements which has contiguous memory location.

Java array is an object which contains elements of a similar data type. The elements of an array are stored in a contiguous memory location. It is a data structure where similar elements are stored.

Arrays in Java work differently than they do in C/C++. Following are some important points about Java arrays.

  • In Java all arrays are dynamically allocated.
  • Since arrays are objects in Java, we can find their length using the object property length. This is different from C/C++ where we find length using sizeof .
  • A Java array variable can also be declared like other variables with [] after the data type.
  • The variables in the array are ordered and each have an index beginning from 0.
  • Java array can be also be used as a static field, a local variable or a method parameter.
  • The size of an array must be specified by an int or short value and not long.
  • The direct superclass of an array type is Object.
  • Every array type implements the interfaces Cloneable and java.io.Serializable.

Types of Array in java

There are two types of array.

  • Single Dimensional Array
  • Multidimensional Array

One-Dimensional Arrays :
The general form of a one-dimensional array declaration is

type var-name[];

OR

type[] var-name;

An array declaration has two components: the type and the name. type declares the element type of the array. The element type determines the data type of each element that comprises the array.

Instantiating an Array in Java

When an array is declared, only a reference of array is created. To actually create or give memory to array, an array is created like :

 var-name = new type [size];

Here, type specifies the type of data being allocated, size specifies the number of elements in the array, and var-name is the name of array variable that is linked to the array.

Example:

int intArray[];    //declaring array

intArray = new int[20];  // allocating memory to array

OR

int[] intArray = new int[20]; // combining both statements in one

Accessing Java Array Elements using for Loop

Each element in the array is accessed using its index. The index begins with 0 and ends at (total array size)-1. All the elements of array can be accessed using for Loop.

 

// accessing the elements of the specified array

for (int i = 0; i < arr.length; i++)

  System.out.println("Element at index " + i + " : "+ arr[i]);

Multidimensional Arrays

Multidimensional arrays are arrays of arrays with each element of the array holding the reference of other array. These are also known as Jagged Arrays.

A multidimensional array is created by appending one set of square brackets ([]) per dimension. 

int[][] intArray = new int[10][20]; //a 2D array or matrix

int[][][] intArray = new int[10][20][10]; //a 3D array

for example an array

int arr[][] = { {2,7,9},{3,6,1},{7,4,2} };

is represented like



this keyword in Java

The “this” keyword refers to the current object in a method or constructor. In Java, this is a reference variable that refers to the current object.

The most common use of this keyword is to eliminate the confusion between class attributes and parameters with the same name.

this keyword can also be used:

  1. to refer current class instance variable.
  2. to invoke current class method (implicitly)
  3. to invoke current class constructor.
  4. this can be passed as an argument in the method call.
  5. this can be passed as argument in the constructor call.
  6. this can be used to return the current class instance from the method.

Example:

public class Main {

  int x;

   // Constructor with a parameter

  public Main(int x) {

    this.x = x;

  }

  // Call the constructor

  public static void main(String[] args) {

    Main myObj = new Main(5);

    System.out.println("Value of x = " + myObj.x);

  }

}

static keyword in java

static is a non-access modifier in Java which is applicable for the following:

  1. blocks
  2. variables
  3. methods
  4. nested classes

To create a static member (block,variable,method,nested class), precede its declaration with the keyword static.

When a member is declared static, it can be accessed before any objects of its class are created, and without reference to any object.

If computations are needed in order to initialize static variables, a static block is declared that gets executed exactly once, when the class is first loaded.

When a variable is declared as static, then a single copy of variable is created and shared among all objects at class level. Static variables are, essentially, global variables. All instances of the class share the same static variable.

When a method is declared with static keyword, it is known as static method. The most common example of a static method is main( ) method. Any static method can be accessed before any objects of its class are created, and without reference to any object. Methods declared as static have several restrictions:

  • They can only directly call other static methods.
  • They can only directly access static data.
  • They cannot refer to this or super in any way.

A static class is a class that is created inside a class, is called a static nested class in Java. It cannot access non-static data members and methods. It can be accessed by outer class name.

  • It can access static data members of the outer class, including private.
  • The static nested class cannot access non-static (instance) data members or methods

Cleaning Up Unused Objects (Garbage Collection)

Some object-oriented languages require keeping track of all the objects that are created, and they explicitly destroyed when they are no longer needed. Managing memory explicitly is tedious and error-prone.

The Java platform allows to create objects as wanted, and no need to worry about destroying them. The Java runtime environment deletes objects when it determines that they are no longer being used. This process is called garbage collection.

Garbage Collection is process of reclaiming the runtime unused memory automatically. In other words, it is a way to destroy the unused objects.

An object is eligible for garbage collection when there are no more references to that object. References that are held in a variable are usually dropped when the variable goes out of scope.

An object can be unreferenced by:

  • By nulling the reference

Employee e=new Employee();  

e=null;  

  • By assigning a reference to another

Employee e1=new Employee();  

Employee e2=new Employee();  

e1=e2;//now the first object referred by e1 is available for garbage collection  

  • By anonymous object etc.

new Employee();  

Finalization

The Garbage collector of JVM collects only those objects that are created by new keyword. So if any object created without new, finalize method is used to perform cleanup processing (destroying remaining objects).

Before an object gets garbage-collected, the garbage collector gives the object an opportunity to clean up after itself through a call to the object's finalize method. The finalize() method is invoked each time before the object is garbage collected. This method can be used to perform cleanup processing. This process is known as finalization.

The finalize method is a member of the Object class, which is the top of the Java platform's class hierarchy.

This method is defined in Object class as:

protected void finalize(){}  

A class can override the finalize method to perform any finalization necessary for objects of that type.

gc() method

The gc() method is used to invoke the garbage collector to perform cleanup processing. The gc() is found in System and Runtime classes.

Garbage collection is performed by a daemon thread called Garbage Collector(GC). This thread calls the finalize() method before object is garbage collected.

public static void gc(){}  

Example:

public class TestGarbage{  

 public void finalize(){

System.out.println("object is garbage collected");

}  

public static void main(String args[]){  

  TestGarbage s1=new TestGarbage();  

  TestGarbage s2=new TestGarbage();  

  s1=null;  

  s2=null;  

  System.gc();  

 }  

Constructor Overloading in Java

Constructor overloading in Java is a technique of having more than one constructor with different parameter lists.

They are arranged in a way that each constructor performs a different task. They are differentiated by the compiler by the number of parameters in the list and their types.

Example:

class Student{  

    int id;  

    String name;  

    int  age;

//creating a two argument constructor  

    Student(int i,String n){  

    id = i;  

    name = n;  

    }  

//creating a three argument constructor  

    Student(int i,String n,int a){  

    id = i;  

    name = n;  

    age=a;  

    }  

    //method to display the values  

    void display(){

                System.out.println(id+" "+name+" "+age);

    }  

    public static void main(String args[]){  

    //creating objects and passing values  

    Student s1 = new Student(111,"Kalyan");  

    Student s2 = new Student(222,"Ashraf",25);  

    //calling method to display the values of object  

    s1.display();  

    s2.display();  

   }  

}

In above example, there are two constructors with different number of parameters. Corresponding constructor is called depending on parameters using to initialize the object.