Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Thursday, 13 October 2016

method overriding in java ?


What do you mean by method  overriding? Why it is needed? Explain the uses of this and super keyword with example.




The benefit of overriding is: ability to define a behavior that's specific to the subclass type, which means a sub class can implement a parent class method based on its requirement.

In object-oriented terms, overriding means to override the functionality of an existing method

Method Overriding:

Method overriding means have same signature but with different implementation.

If subclass (child class) has same method as declared in the parent class, it is known as method overriding in java.

In other words, if sub class provides the specific implementation of a method that is already provided by its super class. it is known as

method overriding.

Super class reference can be used to refer to a subclass object. The dynamic method dispatch mechanism in java selects the appropriate version of an overridden method to execute based on the class of the executing object, not the type of a variable that references that object. 

Usage of java Method Overriding:

Method overriding is used to provide specific implementation of the method that is already provided by its super class. 

Method overriding is used for runtime polymorphism.

Why it is Needed?

Method overriding in object oriented programming is a language feature that all allows a subclass or child class to specific implementation of a method that is already provided by one of its super classes or parent classes.

The implementation in the subclass override(replaces)the implementation in the super class by providing a method that has same name, same parameters or signature and same return type as the method in the parent class.

Super keyword:

super keyword in java is a reference variable that is used to refer parent class object super class an implicit keyword create by JVM and supply each and every java program for performing impotent in three places:

---> At variable level
---> At method level
---> At constructor level

Need of super keyword:

Whenever the derived class is inherits the base class features there is a possibility that base class features are similar to derived class features and JVM gets an ambiguity.

In order to different between base class features and derived class feature must be preceded by super keyword.

Usage of java super Keyword:

1. super is used to refer immediate parent class instance variable.
2. super() is used to invoke immediate parent class constructor.
3. super is used to invoke immediate parent class method.


Real example of Java Method Overriding:

Consider a scenario, Bank is a class that provides functionality to get rate of interest. But, rate of interest varies according to banks. For example, SBI, ICICI and AXIS banks could provide 8%, 7% and 9% rate of interest.




Example:

class A
{
int i;
A()
{
}
A(int i)
{
this.i=i;
}
void print()
{
System.out.println(this.i);
}
}
class B extends A
{
int k;
B(int k)
{
super(k);
this.k=k;
}
B()
{
super.i=5;
this.k=5;
}
void print()
{
super.print();
System.out.println(this.k);
}
public static void main(String s[])
{
B b1=new B(50);
b1.print();
}
}


OutPut:
50
50

Wednesday, 12 October 2016

Explain the use of finalize method with Example


 Explain the use of 

 finalize method with Example 




Finalize() Method:

  • When you will need to do some actions when an object is destroyed by garbage collection.
  • For example when your program is using some non-java resources, you have to free the memory for these resources.
  • This process is known as finalization.
  • The finalization is done by the finalize() method.


Syntax :

protected void finalize()
{
//statements to be executed
}

  • Finalize() method does not return any value so the return type is void.
  • The finalize() mehod is called just before when java runtime system perform garbage collection.
  • Finalize method is object class method, so applied all the class.
Example :

class Demo
{
static int cnt=0;
protected void finalize()
{
cnt++;
System.out.println
                ("Finalize"+ cnt);
}
public static void main(String[] a)
{
int i;
Demo obj[] = 
                new Demo[10000000];
for (i=0;i<10000000;i++)
{
obj[i]s=new Demo();
}
for (i=0;i<10000000;i++)
{
obj = null;
}
System.gc();
}
}



Tuesday, 11 October 2016

Java Pass By Value and Pass By Reference


 Java Pass By Value and Pass By  Reference 




Pass by Value


In java we have a pass by value, when we use primitive type as parameters then it is a pass by value. Thus, what occurs to the parameter that receives the argument has no affect outside the method.
This method is copy of the passed-in variable is copied into the argument. Any changes to the argument do not affect the original one.
Actual parameter expressions that are passed to a method are evaluated and a value is derived. Then this value is stored in a location and then it becomes the formal parameter to the invoked method. This mechanism is called pass by value and Java uses it.





Pass by Reference


In java we use the reference type as parameters in a method then it become a pass by value for the reference value. The reference type refer to an object, so when we use the reference data type as a parameter, a copy of the reference value is made available to the invoked method, which enables the invoked method to work on the same object as the one reference by the invoking method.

In pass by reference, the formal parameter is just an alias to the actual parameter. It refers to the actual argument. Any changes done to the formal argument will reflect in actual argument .


We have a method defined as follows:

 public void method(Account ac,int i)
 {
i+=100;
ac.deposit(10000);
i+=100;

ac = new CurrentAccount
  (1005, “tom”,4000);

i+=100;
ac.deposit(3000);
 }


This method is beging used from another code as follows:


1 Account ac = 
   new CurrentAccount(1005, “tom”, 2000);

2 int a = 100;

3 ac.deposit(3000);

4 method(ac,a);

5 System.out.println
   (ac.getBalance()+”, “+a);

It prints “15000, 100”


Since primitive types are pass by value, the value of a is unchanged. In line 1, balance in Account(ac) is 2000, in line 3 balance in ac 5000. Now the reference to ac is copied to the parameter ac in method, so ac in method refers to the same object ac which is declared in line 1. In line 7, the balance would be 15000, now line 9 makes ac in the method ac in method refer to a new object, so the object refered by ac in line 1 is unaffected. line 9 would make the method loose the reference to the object which was passed as a parameter in line 4.
Example:

class A
{
void print(int i) 
        //pass by value
{
System.out.println(i);
}
public String toString()
{
return "Class A";
}
void toPrint(A obj) 
        //pass by reference
{
System.out.println(obj);
}
}
class B extends A
{
public static void main(String[] str)
{
B obj = new B();
obj.print(5); 
                //pass by value
obj.toPrint(new B()); 
                //pass by reference
}
}






Searches related to java Pass By Value and Pass By Reference

Saturday, 1 October 2016

Features of java

Features of java: 


  • The java programming language has a number of features that make it the language Of choice for most developers .The reason why java is so popular that it is object oriented platform independent does not use pointers has support for multi-threading has a robust exception handling mechanism has good security. Features allows us to create applets and Servlets for use on the web. 


1. Compiled and interpreted:

   A computer language is either compiled or interpreted.

   Java combines both features therefore it is two stage system.

   First java compiler translate source code into byte code and byte code is not machine
instruction therefore interpreter translate byte code into machine code.

2. Platform independent and interpreted:

   Java programs can be easily moved from one computer system to another system.

   If you upgrade in any operating system then it will not affect in the java programs.

3. Object oriented:

   Java is true object-oriented language.

   Almost everything in java is an object.

   Java is an extensive set of classes which are arranged in packages and we can use it by
inheritance.

4. Robust and secure:

   Java a robust language because it provide many safeguards to ensure reliable code.

   It will check data type compile time and runtime.

   Security becomes an important point for a java programming on internet.

5. Distributed:

   Java is designed as a distributed language for creating application on networks.

   It has the ability to share both data and programs.

   In java multiple programmers at multiple remote locations to collaborate and work
together on a single project.

6. Simple small and familiar:

   Java is a small and simple language.

   Many features of C and C++ are not come in java so it become small.

   For example, java does not use pointers, operator overloading, preprocessor header

files, go to statement, multiple inheritance.

   Java has more feature of C and C++ so that java is familiar to us.

7. Multithreaded and interactive:

   Multithreaded means handling multiple tasks simultaneously.

   Java support multithreaded means we need not wait for the application to finish one

task before beginning another task.

   For example, we can listen to an audio clip while scrolling a page.

   This improves interactive program.

8. High-performance:

   Java architecture is defined to reduce error and amount of time.

   So that java gives high performance.

9. Dynamic and extensible:

   Java is dynamic language because it is capable of dynamically linking a new class
libraries, method and classes.

   Java program support functions written in other language such as C and C++.

   These functions are known as native methods.


10.Monitoring and manageability:

   Java supports a number of APIs, such as JVM Monitoring and management interface.

   It manages java programs.


Why java is so popular?


The reason why java is so popular is that it is :

   object-oriented

   platform independent

   Does not use pointer

   support multi-threading

   robust exception handling mechanism

   Full network support

   Good security

   Allows you to create applets and servlets for use on the web.

However, most importantly java is popular because Java is Easy

Friday, 30 September 2016

Initialize Blocks and Class Initialize Java

 Discuss Initialize Blocks and Class Initialize blocks.



 First of all, there are two types of initialization blocks: 


1. Instance Initialization Blocks (Initialization Blocks)
2. Static Initialization Blocks (Class Initialization Blocks).



1. Initializer block


In a class definition, we can have a member block with no name. Such a block is known as the initializer block.

An initializer block is never invoked by any application directly since it does not have any name. However, it is always invoked on an instance as soon as it is allocated.

It is invoked just before the constructor is invoked on the instance. 




Rectangle(int l, int w)
{
 // remove the increment of count from the constructor
setDimensions(l, w);
}
{
 // initializer block, executed whenever any instance is
created.
count++;
 } 


The initializer block in a class is invoked whenever any of the constructor for the class is invoked. This block is always executed before the constructor code is executed.

The initialization process for an instance is thus executed in the following sequence. Whenever any constructor is invoked with the new operator to create a new instance, first the space is allocated for the instance depending on the instance variables declared in the class.

When this space is allocated, its instance variables have the default initial valueaccording to the type of variable, i.e. numeric types will be 0, boolean types will be false and reference types will be null; now in case the instance variable declaration has an assignment, then such an assignment will be executed on the instance; for example, in caseof the Rectangle class, if the instance variable length were declared as

int length = 7; // instance declaration with assignment


then the assignment length = 7 would be executed initially. Now after executing instance variable initialization,  the initializer block would be executed, and then it is followed by execution of the specific constructor code that is invoked.





2. Class Initializer Block

Just like we have the constructor for initializing the instance variables, we use the class initializer block to initialize the class variables.

A class initializer block is created just like the initializer block, but it is declared to be static. We also call this block as the static block.

We also call this block as the static block, e.g. we may declare a static block as given

below...


class Rectangle
{
                static int count;
                static
                {
                                count = 0;
                                System.out.println("Inside a class initializer
                                block");
                }
}



Just like the initializer block, the class initializer block does not have a name and is 
not invoked directly by an application. This block is automatically executed whenever the 
class is loaded.


A class is normally loaded only once at the runtime. The class would be loaded by 
the JVM only if the class is used in an application.

Difference between Initialize Block & Class Init Block


The static block is only loaded when the class object is created by the JVM for the 
1st time whereas init {} block is loaded every time class object is created. Also first the static 
block is loaded then the init block. 






public class LoadingBlocks {
          static
          {
                   System.out.println("Inside static");
          }
          {
                   System.out.println("Inside init");
          }
          public static void main(String args[])
          {
                   new LoadingBlocks();
                   new LoadingBlocks();
                   new LoadingBlocks();
          }
}
Output:
          Inside static
          Inside init
          Inside init
          Inside init







This code should illustrate in which order they both are executed
public class Test
{
                 static int staticVariable;
                 int nonStaticVariable;
                 // Static initialization block:
                 // Runs once (when the class is initialized)
                 static
                 {
                                                System.out.println("Static initalization.");
                                                staticVariable = 5;
                 }
                 // Instance initialization block:
                 // Runs each time you instantiate an object
                 {
                                 System.out.println("Instance initialization.");
                                 nonStaticVariable = 7;
                 }
                 public Test()
                 {
                                System.out.println("Constructor.");
                 }
                 public static void main(String[] args)
                 {
                                 new Test();
                                 new Test();
                 }
}
Output :
                Static initalization.
                Instance initialization.
                Constructor.
                Instance initialization.
                Constructor.




IN SHORT :

Initializer block is used to define the activity that is required to be carried out whenever any instance is created for the class. There can be any number of initializer blocks in a class definition. These would be combined and treated as one initializer block. This code is executed just before any of the constructor code is executed. 

Class initializer block is used to initialize the class variables. This block is executed only once when the class is loaded, and similar to the initializer block in a class definition we can have any number of class initializer blocks, which would be combined and treated as
one.

Labels

ADVERTISEMENT