Showing posts with label what is java inner lass. Show all posts
Showing posts with label what is java inner lass. Show all posts

Thursday, 13 December 2018

Inner Class in Java | What is java inner class and its advantage - Online Help

Inner class in java:

An inner class in java is nothing but, a class within another class is called an inner class. When the programmer wants to restrict the access of the entire code of a class, creates an inner class as a private class. The way to access the inner class is through its outer class only.
  • An inner class in java is a safety mechanism.
  • An inner class is hidden in outer class from other classes.
  • Only the inner class can be private.
  • An object to inner class can be created only in its outer class.
  • An object to an inner class cannot be created in any other class.
  • Outer class object and inner class object are created in a separate memory location.
  • Outer class members are available to the inner class object.


Program:
class bank
{
private double bal,rate;
bank(double b,double r)
{
bal=b;
rate=r;
}
void dispalay()
{
interest in= new interest();
in.calculateInterest();
System.out.println("new balance:"+bal);
}
private class interest
{
void calculteInterest()
{
System.out.println("Balance="+bal);
double interest=bal*rate/100;
System.out.println("interst="+interest);
bal+=interest;
}
}
}
class innerdemo
{
public static void main(String args[])
{
bank account=new bank(20000,5);
account.display();
}
}
output:
Balance=20000.0
interest=1000.0
new balance=21000


Advantages of inner class in Java

 There is basically three advantage of inner class in java. They are as follows:

  • The nested class represents a special type of relationship that is it can access all the members(data members and methods) of the outer class including private.
  • Nested classes are used to develop more readable and maintainable code because it logically groups the class and interfaces in one place only.
  • code optimization: it requires less code to write.
       I think you guys will understand what is an inner class in Java from this post. Guys, actually it's my first blog, if you have any queries, please let me know with your precious comment and it will help me to improve my blog. Thank you so much for visiting my blog.