Header Ads

Object Oriented Programming

 



Object is the physical as well as logical entity whereas class is the only logical entity.

class: Class is a blue print which is containing only list of variables and method and no memory is allocated for them. A class is a group of objects that has common properties.

A class in java contains:

Data Member
Method
Constructor
Block
Class and Interface 

Object: Object is an instance of class; object has state and behaviors.

An Object in java has three characteristics:

State
Behavior Identity
Identity

State: Represents data (value) of an object.

Behavior: Represents the behavior (functionality) of an object such as deposit, withdraw etc.

Identity: Object identity is typically implemented via a unique ID. The value of the ID is not visible to the external user. But it is used internally by the JVM to identify each object uniquely.

Class is also can be used to achieve user defined data types.

difference between class and object

Inheritance: When one object acquires all the properties and behaviors of parent object i.e. known as inheritance. It provides code reusability. It is used to achieve runtime polymorphism.

Abstraction: Data abstraction refers to, providing only essential information to the outside world and hiding their background details, i.e., to represent the needed information in program without presenting the details.

Hiding internal details and showing functionality is known as abstraction. For example: phone call, we don't know the internal processing. In java, we use abstract class and interface to achieve abstraction.

Encapsulation: Binding (or wrapping) code and data together into a single unit is known as encapsulation. For example: capsule, it is wrapped with different medicines.

A java class is the example of encapsulation. Java bean is the fully encapsulated class because all the data members are private here.

Polymorphism: Polymorphism in java is a concept by which we can perform a single action by different ways. Polymorphism is derived from 2 Greek words: poly and morphs. The word "poly" means many and "morphs" means forms. So, polymorphism means many forms.

There are two types of polymorphism in java: compile time polymorphism and runtime polymorphism. We can perform polymorphism in java by method overloading and method overriding.

If you overload static method in java, it is the example of compile time polymorphism. Here, we will focus on runtime polymorphism in java.

Runtime Polymorphism in Java

Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an overridden method is resolved at runtime rather than compile-time.

In this process, an overridden method is called through the reference variable of a superclass. The determination of the method to be called is based on the object being referred to by the reference variable.

Message Passing: Objects can communicate with each other's by passing message same as people passing message with each other. Objects can send or receive message or information. Message passing involves name of object, name of function (message) and information to be send.

For example, student.mark(name). Here student is object, mark is message, name is information.

Variable:

Variable is a memory location where actual values are stored. Variable is one whose value always changes throughout the program. In another words Variable is nothing but its name given to a data.

The variable gives following information i) The data type it can hold ii) Its name iii) Its value 

We distinguish between the lifetimes of variables in 3 contexts with respect to the class

1) Instance Variables (Non-static variables): Instance Variables are members of a class and created for each object of the class and will have its own copies of these variables which are local to the objects. The values of these variables at any given time constitute the state of the object. Instance variables exist as long as the object they belong exists. Instance variables with same names cannot be in a single class.

2) Static Variables (class variables): Static Variables are also the members of a class, but not created for any object of a class and therefore belong only to the class. They are created when the class is loaded at runtime and exist as long as the class exists. Only one copy of static variable is created and gets shared amongst all the object.

3) Local Variables: Variables which are declared inside methods or the block are called as local variable. Local variable is created for each execution of the method or block. After the execution of the method or blocks, Local variables are no longer accessible.

Access Specifiers - There are four types of access specifiers present in Java

These are:

(1) public
(2) no-access or default access
(3) protected
(4) private

Classes encapsulate the data-members and methods defined inside them. According general conventions of OOP, the implementations of the methods and the data-members should remain hidden inside the class body, by default. The class programmer can control the access to the members of the class. The users of the class can access only those members which the class- programmers allows.

There are four levels of access. control in Java, one of them is default (also called as friendly access) Java defines three keywords to specify the access control for the members of the class as well as for the class it-self. These are: private, protected and public. One of these keywords can be written before any member declaration or definitionIn above example the data-member sum, of the class Some Class is declared as private member of the class and the method as public member. Following points discuss the use and working of these keywords.

private:

1. Private members of a class are accessible only inside the class. i.e. these members can be accessed only by the other members of the same class.
2. Classes cannot be private, but inner classes
3. Private members are not accessible out of the class anywhere as well as not accessible to the sub-classes i.e. private members of class are not inherited into sub-classes.
4. Usually the data-members of a class are kept private. Sometimes, methods are declared private, if these methods are to be used inside the class only, and not to be accessed by outsiders.
5. Obviously, if private, they will not be accessible outside the current package.

protected:

1. Protected members of a class are accessible inside the body of a class, or to any of its sub- class.
2. Also, protected members of a class are accessible in the classes in the same package, through object of that class. For other classes they behave like private members of the class.
3. A protected member of a class is inherited into the sub-class with the same access control hence, for a sub-class of a sub-class the member is accessible.
4. Normal class cannot be declared protected, but inner class can be protected.

public :

1. public members of a class are accessible inside the class, as well as anywhere outside the class also.
2. These members of a class accessible to any part of a program, but through object of class. 
3. If member is public and static it can be accesses by any part of a program by using class name directly.
4. Public members are accessible to the sub-classes lying anywhere in the program i.e. inside the same package or outside the package.
5. If class or a class member is declared public it can be used outside the package also.
6. A class is declared public to make it accessible outside the current package.

default access: .

1. When members of a class are defined without any access specifier, they are given a default access. Such members are partly public i.e. they are accessible to the other parts of the program (through objects) which are in the same package.
2. Also, they are inherited into sub-classes with same default access and are accessible in the subclasses.
3. If a class is defined without any access specifier i.e. with default access, the class is accessible to the classes in the current package. 

Ex.
class Data
{
     private int m;      // private variable
     private int n;       // private variable
     int p;                 //default variable
     
     public void setdata()    // public method
     {
          //code
      }
   // code for other members.
}

Static Variables and Static Methods

Static variables are declared outside the method and constructor. Variables and methods can be' declared as static by preceding declaration by a keyword static and these are known as static variables. There is only one copy of the static variable that exists for a particular class. These members are common to all objects and belong to the class. They are defined as follows:

static int count;                          // static variable
static void SomeFunction();                   // static method

static members are accessed using the class name followed by the dot (.) operator. Since these members belong to a class rather than individual objects they are known as class variables and class methods. static variable is useful is to keep count of how many objects of a class are created. When same data need to be shared by all the objects, we declare that variable as static.

Rules for declaring Static Members:

1. Object of a class cannot refer static members.
2. static method can access only static variables.
3. static variables can't refer to 'this' keyword or super keyword in any way.
4. To initialize the static variables, they should be declared inside a block which is executed once when class is loaded.
5. The block should be preceded by a keyword called as static.
6. static members can be accessed direct without creating object of a class.
7. If static method to be called is present in another class then it is called by classname.methodname()
8. If static method is to be called is present in same class then it can be called by its name only. 

Program1:

Code

class Demo 
{ 
  static void fun () 
  { 
    System.out.println("Hello!"); 
  } 
  public static void main (String x[ ]) 
  { 
    fun (); //fun is a static method and main is static therefore main can call fun directly. 
    Demo.fun(); // fun can be called through class name since fun is static. 
    Demo x=new Demo(); 
    x.fun();             //fun can also be called through reference name 
  }
} 
Output:

Hello!
Hello!
Hello! 

Program2:

Code

class Demo 
{ 
   public static void main (String f[ ]) 
   { 
     Demo x=new Demo (); 
     x.funl(); 
   } 
   static void fun() 
   { 
     System.out.println("Hello!"}; 
   } 
   void fun1() 
   { 
     System.out.println("Hi"); 
     fun(); // fun is called directly from a non-static method.
     Demo.fun(); // fun is called from non-static method through class name. 
     Demo x=new Demo(); 
     x.fun(); //fun is called from a non-static method through object name. 
  }
}
Output:

Hi
Hello!
Hello!
Hello!

Program3:

Code

class MathOperation { 
   static int mul(int x,int y) 
   { 
     return(x*y); 
   } 
   static int divide(int x,int y) 
   { 
     return(x/y); 
   }
}
class MathApplication 
{ 
  public static void main(String args[]) 
  { 
    int a = MathOperation.mul(3,5); 
    System.out.println("a ="+a); // a=15 

    int b = MathOperation.divide(a,2); 
    System.out.println("b ="+b); //b=7 
  }
}
Output:

a = 15
b = 7

Difference between non-static and static variable:

difference between non-static and static variables

Note: static variable not only can be access with class reference but also some time it can be accessed with object reference.

Difference between Static and non-static method in Java

In case of non-static method memory is allocated multiple time whenever method is calling. But memory for static method is allocated only once at the time of class loading. Method of a class can be declared in two different ways

1. Non-static methods
2. Static methods

Difference between non-static and static Method 

difference between non-static and static methods

Note: In some cases, static methods not only can access with class reference but also can access with object reference.

Difference between Method and Constructor?

difference between method and constructor

static block in java

static block is a set of statements, which will be executed by the JVM before execution of main method. At the time of class loading if we want to perform any activity, we have to define that activity inside static block because this block executes at the time of class loading.
In a class we can take any number of static block but all these blocks will be executed from top to bottom.

Syntax

static
{
    …………………….
    //Set of Statements
    ……………………
}

Note: In real time application static block can be used whenever we want to execute any instructions or statements before execution of main method.

Example of static Block -

Code

class StaticDemo 
{ 
  static
  { 
    System.out.println("Hello how are u ?"); 
  }
  public static void main(String args[]) 
  {
    System.out.println("This is main()"); 
  }
}
Output

Hello how are u?
This is main() 

Run java program without main method

Code

class Static Demo 
{ 
  static 
  { 
    System.out.println("Hello how are u ?"); 
  } 
} 
Output:

Hello how are u?
Exception is thread "main" java.lang.no-suchmethodError: Main

Note: "Exception is thread "main" java.lang.no-suchmethodError: Main" warning is given in java 1.7 and its above versions

More than one static block in a program 

Code

class StaticDemo 
{ 
  static 
  { 
    System.out.println("First static block"); 
  } 
  static 
  { 
    System.out.println("Second Static block"); 
  }
  public static void main(String args[]) 
  {
    System.out.println("This is main()"); 
  } 
} 
Output
First static block
Second static block
This is main

Note: "Here static block run according to their order (sequence by) from top to bottom.

Why a static block executes before the main method?

A class has to be loaded in main memory before we start using it. Static block is executed during class loading. This is the reason why a static block executes before the main method. 

Constructors

Constructor will be called automatically when the object is created. Constructor name must be similar to name of the class. Constructor should not return any value even void also. Because basic aim is to place the value in the object. (if we write the return type for the constructor then that constructor will be treated as ordinary method). Constructor definitions should not be static. Because constructors will be called each and every time, whenever an object is creating.

Constructor should not be private provided an object of one class is created in another class (Constructor can be private provided an object of one class created in the same class). Constructors will not be inherited from one class to another class (Because every class constructor is created for initializing its own data members). The access specifier of the constructor may or may not be private.

If the access specifier of the constructor is private, then an object of corresponding class can be created in the context of the same class but not in the context of some other classes. If the access specifier of the constructor is not private, then an object of corresponding class can be created both in the same class context and in another class context. The main purpose of a Constructor is to initialize the Object. If there is no constructor defined by the programmer, then JVM automatically executes the default constructor.

Default constructor: A constructor having no parameters is called the default constructor.

1. If you define no constructors at all for a class, a trivial default constructor (with the empty body) is automatically generated.
2. If you define any constructor, no default constructor is generated automatically and you will have to write your own.
3. It is a good idea to have a default constructor, because client programmers usually assume its existence.

Program: 

Code

class Demo 
{ 
  Demo()   //default constructor 
  { 
   System.out.println("\nHello, World!!"); 
  }
  public static void main (String a[]) 
  { 
    Demo x=new Demo(); 
  } 
} 
parameterized Constructor

A constructor which contains variables as parameters is called as parameterized constructor. It can be used to set different values to different objects of same class.

Program

Code

class Employee 
{
  String name, address; 
  long ph; 
  double sal; 
  Employee (String n, String a, long p, double s) //parameterized constructor. 
  { 
    name = n; address = a; 
    ph = p; 
    sal = s; 
  } 
  void display () 
  { 
     System.out.println("Name = +n "address +a "Phone No. : = +p "Salary = "+s); 
  } 
}
class EmployeeDemo 
{ 
   public static void main(String args[]) 
   { 
      Employee e = new Employee("Abhi", "Andheri", 26353993, 60000); e.display(); 
   } 
}
Constructor Overloading

1) When more than one constructor contains different number of parameters and type constructors are said to be overloaded.
2) The proper overloaded constructor is executed based upon the parameters specified when new is executed.
3) When constructor is overloaded then class must have a default constructor.
4) Constructors having same number of parameters then they must be different in the datatype.
5) Overriding is not possible at constructor level because the scope of constructor is within the class so that it is not possible to achieved overriding at constructor level

Program:

Code

class Volume 
{ 
  double v; 
  int len, bre, ht, rad, side; 
  Volume(int 1, int b, int h) 
  { 
    len = 1; 
    bre = b;
    ht=h; 
  }
 Volume(int r, int h) 
 { 
   rad = r; 
   ht = h; 
   v = 3.14 * rad * rad * ht; 
 }
 Volume(int s)
 {
   side=s;
   v=side*side*side;
 }
 Volume() 
 { 
   System.out.println ("Constructor Overloading"); 
 } 
 void display ()
 { 
   System.out.println ("Volume = " +v); 
 } 
}

class OverloadDemo { 
  public static void main (String x []) { 
  Volume obj = new Volume (); 
  Volume obj1 = new Volume (10, 20, 30); 
  obj1.display(); 
  Volume obj2 = new Volume (5, 10); 
  obj2.display(); 
  Volume obj3 = new Volume (13); 
  obj3.display (); 
 }
}
The toString() Method

The toString() method is defined in 'Object' class. The toString() method returns a string that contains a description of the object on which it is called. This method is automatically called when an object reference is passed to print() or println() Method. It is also called when reference is used in concatenation expression. Every class implements toString() because it is defined by object.

General Form: public String toString(); // toString () return the description of an object.

To implement toString(), simply return a string object that contains the human riddle string that approximately describes an object of your class 

Code

class Student 
{ 
  String name; 
  int roll; 
  Student(String s, int r)
  { 
    name=s; 
    roll=r; 
  }
  public string toString( ) 
  {
    return "Name="+name+ "\nRoll no="+roll; 
  }
}

class StudentDemo 
{
  public static void main(String x[]) 
  {  
    Student s1=new Student("Amit",22);  
    String s2="Student Details:\n:" +s1; 
    System.out.println(s1); 
    System.out.println(s2); 
  }
}
Output: 

Name = Amit
Roll no = 22

Student Details:
Name = Amit
Roll no = 22

continue: Continue is used to manually go down to next iteration without reaching the end of the current block. 

Program

Code

class ContinueDemo 
{ 
   public static void main(String args[]) 
   {
     for(int i=0; i <10 ; i++) 
     {  
  	if(i%2==0) 
        {         
          continue; 
        }
      System.out.println(i); 
    } 
  }
}
Output:  1              3               5                      7                  

Label break: In case of a labeled break the break should be followed by the labeled name. 

Code

class LabelBreak 
{ 
  public static void main(String args[]) { 
  One: 
  { 
    Two: 
    { 
      Three: 
      { 
        System.out.println("Before"); 
        if(true) 
        { 
          break Two; 
        } 
       System.out.println("After"); 
      } 
     System.out.println("After3"); 
    } 
   System.out.println("After2"); 
  } 
 System.out.println("After!"); 
 } 
} 
Output:
Before
After2
After1 

Loop break: To throw the control out of loop.

Code

class BreakFor 
{ 
  public static void main(String[] args) 
  { 
   for (int i = 1; i<10; i++) 
   {        
     break;
   } 
  } 
 }
}
Output:    1                        2                      3

‘this’ keyword: It returns the starting memory address of calling.

this : It refers to not static variables. If local variables and non-static variables are having the same name then local variables hides the identity of non-static variables. To access the non-static variables in presence of local variable, we add the 'this' keyword explicitly before every non-static variable.

Code

class This1 
{ 
  int a; 
  This1 (int a) 
  { 
    this.a = a; 
  }
  public static void main(String args[]) 
  { 
     This1 m = new This1(10); 
     System.out.println(m.a); 
   }
 }
Output: 10 

Code

class This2 
{ 
   int x=10; 
   void met() 
   { 
    int x = 40; 
    System.out.println(x+" "); 
    System.out.println(this.x + " "); 
  }
  public static void main(String args[]) 
  {
    This2 m = new This2();
    m.met(); 
    System.out.print(m.x + " "); 
  } 
} 
Output: 40  10 10

this: when non-static method or constructor is executed, java interpreter adds 'this' keyword implicitly before every non-static variable. 

Code

class This3 { 
  String name; 
  int sal; 
  This3(String s, int i) 
  { 
    name=s; 
    sal=i; 
    System.out.println("Name : "+name); 
    System.out.println("Salary: "+sal); 
  } 
  This3(String s) 
  { 
    this(s,0); 
  } 
  This3 (int i) 
  { 
    this("Unknown",i); 
  } 
  This3() 
  { 
    this(0); 
  } 
  public static void main(String args[]) { 
  This3 w = new This3("Maya", 1000); 
  This3 x = new 
  This3("Sangeeta"); 
  This3 y = new This3 (5000); 
  This3 z = new This3(); 
 }
}
Output:

Name: Maya
Salary: 1000
Name: Sangeeta
Salary: 0
Name: Unknown
Salary: 5000
Name: Unknown
Salary: 0

Java is Garbage Collector

C++ allows de-allocating memory space for the object dynamically by using delete operator. In Java, de -allocation takes place automatically. The technique is called as Garbage Collection. When no reference to an object exists, that object is assumed to be no longer needed and the memory occupied by the Object can be reclaimed. There is no explicit need to destroy the object in C++. Garbage Collection can also be known as Litter Recycling. The Garbage Collection runs wherever the system is idle, or when a requested allocation to fails to find enough memory. Garbage Collection can occur sporadically during the execution of your program.

The garbage collector is under the control of the JVM. The JVM decides when to run the garbage collector but there are no guarantees, under any circumstances, that the JVM will comply. JVM will typically run the garbage collector when it senses that memory is running low. When your Java program makes a request for garbage collection by calling System.gc() method, JVM will usually runs garbage Collector but there is no guarantee. When object is without reference or no live thread can access it, such objects are ready for garbage collector.

The garbage collection routines that Java provides are members of the Runtime class. The Runtime class is a special class that has a single object (a Singleton) for each main program. The Runtime object provides a mechanism for communicating directly with the virtual machine. In order to get the Runtime object, you can use the method Runtime.getRuntime(), which returns the Singleton. The simplest way to for garbage collection (remember-just a request) is System.gc();

Theoretically, after calling System.gc(), you will have as much free memory as possible. We say theoretically because this routine does not always work that way. First, the JVM you are using may not have implemented this routine; the language specification allows this routine to do nothing at all. This is not to say that System.gc() is a useless method-it's much better than nothing. You just can't rely on System.gc() to free up enough memory so that you don't have to worry about the garbage collector being run.

The following program lets us know how much total memory the JVM has available to it and how much free memory it has. It then creates 10,000 Date objects. After this, it tells us how much memory is left and then calls the garbage collector (which, if it decides to run, should halt the program until all unused objects are removed). The final free memory result should indicate whether it has run. Let's look at the program: 

Code

import java.util.* ;
class CheckGC 
{ 
  public static void main(String[] args) 
  {
    Runtime rt = Runtime.getRuntime(); 
    System.out.println("Total JVM memory: " + rt.totalMemory()); 
    System.out.println("Before Memory = " + rt.freeMemory()); 

    Date d = null; 
    for(int i=0;i<10000;i++) 
    { 
      d = new Date()); 
      d = null; 
    } 
    System.out.println("After Memory = " + rt.freeMemory()); 
    rt.gc(); // an alternate to System.gc() 
    System.out.println("After GC Memory = " + rt.freeMemory());      
  }
}
Output:

Total JVM memory: 1048568
Before Memory = 703008
After Memory = 458048
After GC Memory = 818272

Finalization

Object sometimes hold the non-java resources such as file handle or window characters front before destroying object of class, these resources must be freed. To handle this situation, java provides a mechanism called Finalization. For this purpose, finalize() method which is called at run time just before destroying the object of a class Inside the finalize () you will specify those actions that must be performed before an object is destroyed.

Finalize is a method of the class object which is called automatically by garbage Collector (gc) when an object becomes unreferenced. The garbage Collector can called explicitly by calling static function gc() of the System class.

                    System.gc();

The finalize method can be used to release resources like files, databases associated with the object.

General form of finalize() method.

                   protected void finalize()
                   {
                        // finalization code
                    }

Here, the keyword protected is specifies that prevents  access to finalize() by code defined outside its class.

Thus, we can say that finalize performs works similar to destructors.

Program

Code

class FinalizeEx 
{
  static int c; 
  FinalizeEx() 
  {
    c++; 
    System.out.println("Object created="+c); 
    c--;
   } 
 }
class FinalizeExDemo
{
  public static void main(String args[]) 
  {
    protected void finalize() 
    {
      FinalizeEx x1=new FinalizeEx();
      FinalizeEx x2=new FinalizeEx(); 
      FinalizeEx x3=new FinalizeEx(); 

      x1=null; 
      x2=null; 
      x3=null; 
     System.gc(); // It calls finalize() method 
     System.out.println("hello"); 
  } 
} 
Output:

Object created=1
Object created=2
Object created=3
hello
Object destroyed=3
Object destroyed=2
Object destroyed=1

Constants  in Java

Constants can be declared in Java. Constant in java can be declared by using the keyword final. The value of cannot change throughout the program. The keyword final indicates that you can assign o the variable some value once then its value doesn't change throughput the program. In Java, by convention, constants are variables generally declared in uppercase only Ex. final int MAX 100; where MAX is an integer constant and its fixed value is 100.

Hash code

When an object is created through a new operator by calling the constructor of the corresponding class, a unique identifier is assigned to the reference variable, known as hash-code. Hash-code is allotted by JVM. This can be seen in the following example:

Program:

class p
{
public static void main (String args[])
{
p x = new p ();
System.out.println(x.hashCode());
}
}

The method hashCode() returns the hash-code of the corresponding reference when an object is created.
Hash-code is assigned to a reference variable only when memory is allocated from the heap area.
The local variables of primitive data types are created inside the stack area and the memory is also allocated from there. However, all the above complexities are not involved here. The local variables of primitive data types do not have any hash-code because they do not acquire memory from the heap area. To get a hash-code, the variable must be of reference type. This is shown by the following example:

Program:

class p
{
public static void main (String f[])
{
int mak=5;
System.out.println (mak.hashCode());
}
}

The above program will result in a compilation error because mak is not a reference variable and memory is not allocated to it from heap. The error is 'int' cannot be dereferenced'. The next question that arises is whether it is possible to allocate memory to variables of primitive data type from heap or not. The answer to this is yes.

System.arraycopy()

If we want copy of an array into another array, we must make a new array of the same length as the original and copy overall values as follows:

double [ ] prices = new double[data.length];
for(int i=0; i < data.length; i++)
{
prices[i] = data[i];
}

Instead of the for loop you can also use the static System.arraycopy method. The method can be used to copy any portion of an array into another array.

System.arraycopy (from, fromStart, to, toStart, count);

from: name of the source array.
fromstart: start position in the source array
to: name of destination array
tostart: position in the second array from where array will get copied. count: no of the elements to be copied from the source array.

To copy the entire data array into the prices array we say:

System.arrayCopy(data,0,prices,0,data.length);

Example

Code

class ArrayCopy 
{
  public static void main(String[] args) 
  { 
    int x[] = {1,2,3,4,5}; 
    int y[] = new int[5]; 
    System.arraycopy(x,0,y,0,5); 
    System.out.println("Array y after copying is :"); 
    for(int i=0;i<5;i++) 
    { 
      System.out.print(" "+ y[i]); 
    } 
  } 
} 
Output:

Array y after copying is: 12345

Command Line Arguments

A Java application can accept any number of arguments from the command line. This allows the user to specify configuration information when the application is launched. The user enters command-line arguments when invoking the application and specifies them after the name of the class to be run. In other way, when the input values are passed along with interpreter's command then it initialise the String array which is nothing but compulsory parameter of main method.

Passing command arguments to a Java program.

Fact

execute java program

passing command arguments to java program

For example, consider the 'Good Morning' program we have written in previous practical, we can modify the program to say Hello to the user executing the program using command line arguments. We have to do following changes,

Example

Code

class Hello 
{ 
  public static void main(String args[]) 
  { 
    String str; 
    str = args[0]; 
    System.out.println("Good" + str); 
  }
}
To execute this program follow these steps
C:\> javac Hello.java
C:\> java Hello Morning
Good Morning

Programs on Command Line Arguments

Q.1 Write a program to reverse a number entered thorough command line arguments

Code

class Reverse 
{
  public static void main(String args[]) 
  { 
    int rem; 
    int num; 
    num = Integer.parseInt(args[0]); 
    System.out.print("Reverse of number is="); 
    while(num!=0) 
    { 
      rem num%10; 
      System.out.print(+rem); 
      num=num/10; 
    } 
  } 
} 
C:\> javac Reverse.java
C:\> java 12
Reverse of number is= 21

Q.2 Write a program to find the largest of any numbers passed to it through command line arguments 

Code

class largest 
{
  public static void main(String args[]) 
  { 
    int i, count, max, temp; 
    count = args.length; 
    max = Integer.parseInt(args[0]); 
    System.out.println(max); 
    for(i=0; i<count; i++) 
    { 
      temp = Integer.parseInt(args[i]); 
      if(temp > max)  
      { 
        max=temp; 
      } 
    } 
  System.out.println("The largest number is " + max); 
 }
}
/*Output
C:\> javac largest.java 
C:\> java largest 2       10       6        20
The Largest number is 20
*/

Difference between Abstraction and Encapsulation 

difference between abstraction and encapsulation

Inner Classes in Java Programming

If one class is existing within another class is known as inner class or nested class

Syntax

class Outerclass_name
{
       ……………………..
       ……………………..

        class Innerclass_name1
        {
             ……………………..
             ……………………..
   
        }
        class Innerclass_name1
       {
             ……………………..
             ……………………..
       }
     ………………..
}

The main purpose of using inner class

To provide more security by making those inner class properties specific to only outer class but not for external classes. To make more than one property of  classes private properties.

Private is a keyword in java language, it is preceded by any variable that property can be access only within the class but not outside of it (provides more security).

If more than one property of class wants to make as private properties than all can capped under private inner class.

Syntax

class Outerclass_name
{
      private class Innerclass_name
      {
           …………………….    // private properties
       }
}

Note : No outer class made as private class otherwise this is not available for JVM at the time of execution.

Rules to access properties of inner classes.

Inner class properties can be accessed in the outer class with the object reference but not directly,  Outer class properties can be access directly within the inner class properties can’t be accessed directly or by creating directly object.

Note : In special situation inner class property can be accessed in the external class by creating  special objects with the reference of its outer class.

Example

Code

class A //outer class
{
  void fun1()
  {
    System out.printIn("Hello fun 1 ()"); /* inner class properties should be access using Object reference in outer class,*/
    B ob = new  B();
    ob.x = 10;
    System.out.printIn("x="+ob.x);
    ob.fun2();
  }
  void fun3()  //outer class fun3()
  {
    System.out.printIn("Hello fun3()");
  }

  class   B  // inner class
  {
     int  x; // inner class variable
     void fun2()   //inner class fun2()
     {
        System.out.printIn("Hello fun2()");
        fun3(); //outer class properties can be access directly
     }
   }
}

  class  C // external class
  {
    void fun3 ()
    {
      System out.printIn("Hello fun3()");
    }
 }

 class IncDemo
 {
   public static void main (String args[ ])
   {
     A oa = new A();
     oa.fun1();
     C oc = new C();
     oc.fun3();
   }
}
Output

Hello fun1()
X = 10
Hello fun2()
Hello fun3()

Accessing inner class properties in the external class

1. If inner class in non static the object can be created with the following syntax

Syntax

class Outer_class
{
   class Inner_class
   {
       ………………….
       ………………….
   }
   ………………….
   ………………….
}

class External_class
{
    Outer_class.Inner_Class objectreference = new Outer_Class.External_Class( );
}

2. If inner class is static then object reference can be created with the following syntax 

Syntax

class Outer_class
{
     static class Inner_Class
     {
          ………………….
          ………………….
     }
}

class External_Class
{
    Outer_class Inner_Class objectrefernce=new Outer_Class External_Class();
}

Example

Code

class A // Outer class 
{
  class B // non-static inner class
  {
    int x;   //inner class variable
    void fun1()    //inner class fun 1()
    {
       System.out.printIn("Hello fun 1()");
    }
}

static class C  //static inner class
{
   int y=20;  // inner class variable
   void fun2()
   {
     System.out.printIn("Hello fun2()");
   }
  }
}
class IncDemo
{
  public static void main(String args[])
  {
    A.B ob = new A().new.B();
    System.out.println(ob.x);
    ob.fun1();
    A.C oc = new A.C();
    System.out.printIn(oc.y);
    oc.fun2()
  }
}
Relationship in Java

Type of relationship always makes to understand how to reuse the feature from one class to another class. In java programming we have three types of relationship they are.

1. Is-A Relation
2. Has-A Relation
3. Uses- A Relationship

Is-A Relationship

In Is-A relationship one class is obtaining the features of another class by using inheritance concept with extends keywords. In a IS-A relationship there exists logical memory space.

Is-A Relationship

Example of Is-A Relation

Code

class Faculty
{
  float salary = 30000;
}
class Science extends Faculty
{
  float bonous = 20000;
  public static void main(String args[])
  {
    Science obj=new Science();
    System.out.printIn("Salary is:"+obj.salary);
    System.out.printIn("Bonous is:"+obj.bonous);
  }
}
Output

Salary is: 30000.0
Bonus is: 2000.0

Has-A  relationship

In Has-A relationship an object of one class is created as data member in another class the relationship between these two classes is Has-A-In  Has- relationship there existed physical memory space and it is also known as part of or kind of relationship. 

Has-A Relationship

Example of Has-A Relation

Code

class Employee
{
   float salary = 30000;
}
class Developer extends Employee
{
  float bonous=2000;
  public static void main(String args[])
  {
    Employee obj=new Employee();
    System.out.printIn("Salary is:"+obj.salary):
  }
}
Output
Salary is: 30000.0

Uses-A relationship

A method of one class is using an object of another class the relationship between these two classes is known as Uses-A relationship
Uses-A Relationship

As long as the method is execution the object space (01) exists and once the method execution is completed automatically object memory space will be destroyed.

Example  of Uses –A Relation

Code

class Employee
{
  float salary = 30000;
}
class Salary extends Employee
{
  void disp()
  {
    float bonous = 1000;
    Employee obj=new Employee();
    float Total=obj.salary+bonous;
    System.out.printIn("Total Salary is:"+Total);
  }
}
class Developer
{
  public static void main(String args[])
  {
    Salary s=new Salary();
    s.disp();
  }
}
Output : Total Salary: 31000.0

Note 1:  The default relationship in java is Is-A because for each and every class in java there exist an implicit predefined super class is java.lang.Object.

Note 2:  The universal example for Has-A relationship is System.out (in Syste,.out statement.out is an object of prinstStream class created as static data member in another system class and printStream class is known as Has-A relationship).

Note 3:  Every execution logic method (main()) of execution logic is making use of an object of business logic class and business logic class is known as User-A relationship.

No comments

Powered by Blogger.