OOPS

Object Oriented Programming in Java
In OOPS we solve our problems in terms of entities or objects that occur in context of our program.So if we are building a racing game we will have an object of  class vehicle or we may have objects of classes Cars,Bikes,Trucks etc depending upon the scope of our game.

Objects
  • An object is an instance of a class.
  • Class is a blueprint from which objects are created.
  • A class is a collection of objects with common properties.A class is a blueprint that goes to makeup a particular sort of object.
  • A subclass is a class that inherits some or all of the properties of its parent class.
  • Object can have a state and behavior
  • For example customer object can have
    • name,age,phone no as state
    • Walking,Buying as behavior
  • An object interacts through methods.


Let's take example of a calculator.

Object of a class have a set of values defined that characterize that particular object.For example Interest Calculator will have ratePercent, Amount etc.

Class
A class is a definition of an object.It defines all the parameters that build up an object.Lets's take example of a class vehicle which will have parameters like speed, no of wheels, type.
These parameters are also called as instance variables or attributes of a class, or class fields.
Instance variables can be basic type of data such as numbers,strings but they can also be other class objects.
A parameter "wheeltype" can be of type "Wheel Class".

 public class vehicle {  
   // variables
   private int speed;  
   private int noOfWheels;  
   private String type;  
   private int distanceRun;  
   private Date serviceDate;  
 }  

Certain keywords like "class","int","String" etc are defined keywords in java hence they cannot be used as variable names or for any other purposes.

Comments in java begin with two successive forward slashes "//".In the above example class first line is a variable which will be ignored by compiler.
Compiler ignores anything that follows the two forward slashes For Example.

Operating on Objects

A class also specifies operations on objects of a class.These are performed by Member Functions.Let us add another variable to our vehicle class "distanceRun".For distance run we will perform certain operations such as checking service status etc.Our class code will be

 import java.util.Date;  
 /**  
  *  
  * @author Gaurav Matta  
  */  
 public class vehicle {  
   private int speed;  
   private int noOfWheels;  
   private String type;  
   private int distanceRun;  
   private Date serviceDate;  
   public vehicle(int speed,int noOfWheels,String type,int distanceRun)  
   {  
     this.speed=speed;  
     this.noOfWheels=noOfWheels;  
     this.type=type;  
     this.distanceRun=distanceRun;  
     this.serviceDate=new Date();  
   }  
   public void updateDistanceRun(int distance)  
   {  
     this.distanceRun=distance;  
   }  
   public int checkWheelChange()  
   {  
     if(this.distanceRun>30000)  
     {  
       return 1;  
     }  
     else  
     {  
       return 0;  
     }  
   }  
   public int checkServiceStatus()  
   {  
     Date d1=this.serviceDate;  
     Date d2=new Date();  
     int diffInDays = (int) ((d2.getTime() - d1.getTime()) / (1000 * 60 * 60 * 24));  
     if (diffInDays>365)  
     {  
       this.serviceDate=new Date();  
       return 1;  
     }  
     else  
     {  
       return 0;  
     }  
   }  
   public static void main(String args[])  
   {  
     vehicle v=new vehicle(180,8,"Truck",50000);  
     int wheelStatus=v.checkWheelChange();  
     System.out.println(wheelStatus);  
   }  
 }  

So what we are checking here is if the distance is greater than 30,000 a wheel change is required.
And at every 10,000 we need to get our car serviced.Of course we have avoided many checks as this is for demo purposes only.

Above file will be saved as vehicle.java.The filename and class name is same always.Each object created will have its own copy of variables.

We have used 2 Access type keywords or identifiers which are public and private there is one more called as protected.

Private ensures that function or variables are only accessible inside the class.
Protected ensures accessibility in derived classes for extension purposes.
Public makes them accessible to outside world.

Each class has a method called constructor which initializes variables of class object.This method has same name as the name of the class.

In above example the top most method is constructor defined as
public vehicle(int speed,int noOfWheels,String type,int distanceRun)

Understanding Program
  1. In start we import date class from java.util library since we are working with Dates.
  2. Then we have a set of member variables speed, noOfWheels etc.
  3. Then we have a constructor which initializes our variables.
  4. Then we have member functions like
    1. updateDistanceRun();
    2. checkWheelChange();
    3. checkServiceStatus();
  5. Then we have main function where we initialize the class
Data Abstraction
To specify a class we need to decide what set of attributes and member functions meet our requirements.This is called as data abstraction. We will Specify all this with the example of Basic Calculator Later.

Overloading
  • Methods with same name but different signature
  • We have overloaded "method" in below example
  •  package javaimplant.overloading;  
     public class MethodOverloading {  
     public void method()  
     {  
     System.out.println("Rose");  
     }  
     public void method(String args)  
     {  
     System.out.println("Roses are "+args);  
     }  
     public static void main(String[] args) {  
     MethodOverloading m=new MethodOverloading();  
     m.method();  
     m.method("Tulips");  
     }  
     }  
Inheritance
  • Classes inherit commonly used state and behavior
  • For example Dog and Cat may inherit features from Mamels class which may define features at an abstract level.
  • We use extends keyword in Java to inherit a class.
  • Child class inherits all methods not marked as private from parent class.
Mamels(Parent Class)
 package javaimplant.inheritance;  
 public class Mamels {  
      String voice;  
      int legs;  
      public void giveSound()  
      {  
           System.out.println("This Mamel gives sound "+voice);  
      }  
      public void giveLegCount()  
      {  
           System.out.println("This Mamel has leg count "+legs);  
      }  
      public String getVoice() {  
           return voice;  
      }  
      public void setVoice(String voice) {  
           this.voice = voice;  
      }  
      public int getLegs() {  
           return legs;  
      }  
      public void setLegs(int legs) {  
           this.legs = legs;  
      }  
 }  
Dog(Child Class)
 package javaimplant.inheritance;  
 public class Dog extends Mamels {  
 }  
    Encapsulation
    • Encapsulation refers to hiding of items(data and methods) in an object.
    • This is done using private keyword.
    • As we can see in the above example all the data members are available via member functions and cant be accessed directly so they are encapsulated.
    • Another advantage of encapsulation is that we can change the internals of a class without having to change its external access.So the programs accessing them from outside need not have to be changed
    • Being able to encapsulate is important for security and integrity of objects.
    This also helps in internal binding so we can make internal changes without having to change external accessibility.

    Classes and Data Types
    A class defines an object it is in some aspects same as defining datatypes for example in the above example we have used Date Class of java.String is also a class in java.
    There are some basic types in java called as primitive types.These are not classes.


    Classes and Subclasses
    Subclasses in java are subsets of currently defined classes for example a subset of vehicle class can be "Two Wheelers","Cars","Jeeps","Buses" etc.
    Such classes are called as derived classes.

    Java Class Library
    • A library in java is a collection of classes providing related facilities,which we can use in our programs.
    • These libraries help you in writing Java programs easier.
    • For example "The Standard Class Library" provides functionalities like sending out output,output with a line break etc.
    • A class library is a set of class files.
    • These classes are grouped together into related sets called as packages,and each package is stored in a separate directory.
    • A class in a package can access any of the other classes in the package unless access type is Private.
    • A class in another package may or may not be accessible.
    • When we don't define a package classes are stored in "default package".
    • Package Name is based on the path to the directory in which the classes belonging to the package are stored.For example java.lang package is stored in java\lang path.
    Some of the frequently used packages in JDK are
    1. java.lang: These classes support the basic language features and the handling of Array & Strings.Classes in this package are always available directly in programs by default because this package is automatically loaded.
    2. java.io: Classes for input and output operations.
    3. java.util: This package contains utility classes of various kinds, including classes for managing data within collections or groups of data items.
    4. javax.swing: These classes provide easy to use and flexible components for building graphical user interfaces(GUI's).The components in this package are referred to as Swing components.
    5. java.awt: Classes in this package provide the original GUI components as well as some basic support necessary for Swing Components.
    6. java.awt.geom: These classes define 2 dimensional geometric shapes.
    7. java.awt.event: The classes in this package are used in the implementation of windowed applications to handle events in our programs.These events are related to windows such as click,doubleclick etc.
    To use classes from other packages than java.lang we use import statements as we can see we used
    import java.util.Date;  

    We can import names of all classes in a package using
    import java.util.*;  
    Standard classes do not appear as files or directories in our harddisk. They are packaged in a single compressed file "rt.jar" that is stored in jre/lib.
    A "*.jar" file is a Java archive file.

    Java Applications
    • Every Java application has a class which has the main() method.
    • The name of the the class is the name that we use as argument passed to the interpreter during execution.
    • The main() method is first method which is executed.
    • This is the first method executed in an application.This method has a particular format which is
    public static void main(String args[])  
    {  
    System.out.println("Hello World");
    }
    • Public indicates that it is globally accessible.
    • Static ensures it is accessible even though no objects of class exist.
    • System is the name of the standard class that contains objects that encapsulate the standard I/O devices for our system.
      • System.out.println(wheelStatus); 
    • Object out represents the standard output stream.Out is a static method which means Out exists even though there are no objects of the type System.
    • Println() method belongs to object out and output's a string that appears between the parenthesis to your display.
    Java and Unicode
    Unicode is a standard character set that was developed to allow the characters necessary for almost all languages to be encoded.It uses a 16 bit code to represent a character i.e. upto 65,535 non-zero character codes can be distinguished.
    Java  source code is in Unicode characters.Comments,Identifiers,Character and String literals can all use any characters in the Unicode set that represent letters.
    ASCII set corresponds to the first 128 characters of the Unicode set.

    When I execute the above program here is what I get
    Static Variables
    • A variable declared as static is shared by all the instances of the class and its subclass instances.
    Example of Basic Calculator
      1. Instance Variables
        1. Digit 1
        2. Digit 2
      2. Member Functions
        1. Add
        2. Subtract
        3. Divide
        4. Multiply
        5. Percentage
      There can be many more as we can add as much functionality as we like.In Java definition of class calculator will be something like.
       public class calc {  
         private final int digit1;  
         private final int digit2;  
         public calc(int digit1,int digit2)  
         {  
           this.digit1=digit1;  
           this.digit2=digit2;  
         }  
         public int add()  
         {  
           return digit1+digit2;  
         }  
         public int subtrct()  
         {  
           return digit1-digit2;  
         }  
         public int divide()  
         {  
           return digit1/digit2;  
         }  
         public int multiply()  
         {  
           return digit1*digit2;  
         }  
         public int remainder()  
         {  
           return digit1%digit2;  
         }  
         public void swap()  
         {  
           int d1=this.digit1;  
           int d2=this.digit2;  
           System.out.println("Digit 1 is "+d1+" it's Binary :"+Integer.toBinaryString(d1));  
           System.out.println("Digit 2 is "+d2+" it's Binary :"+Integer.toBinaryString(d2));  
           d1^=d2;  
           System.out.println("After d1^=d2");  
           System.out.println("Digit 1 is "+d1+" it's Binary :"+Integer.toBinaryString(d1));  
           System.out.println("Digit 2 is "+d2+" it's Binary :"+Integer.toBinaryString(d2));  
           d2^=d1;  
           System.out.println("After d2^=d1");  
           System.out.println("Digit 1 is "+d1+" it's Binary :"+Integer.toBinaryString(d1));  
           System.out.println("Digit 2 is "+d2+" it's Binary :"+Integer.toBinaryString(d2));  
           d1^=d2;  
           System.out.println("After d1^=d2");  
           System.out.println("Digit 1 is "+d1+" it's Binary :"+Integer.toBinaryString(d1));  
           System.out.println("Digit 2 is "+d2+" it's Binary :"+Integer.toBinaryString(d2));  
         }  
         public void increment()  
         {  
           System.out.println("Digit 1 is :"+this.digit1);  
           int d1=this.digit1;  
           System.out.println("Digit 1++ is :" + (d1++));  
           System.out.println("Now Digit 1 is :" + d1);  
           d1=this.digit1;  
           System.out.println("++Digit 1 is :" + (++d1));  
           System.out.println("Now Digit 1 is :" + d1);  
         }  
         public void decrement()  
         {  
           System.out.println("Digit 1 is :"+this.digit1);  
           int d1=this.digit1;  
           System.out.println("Digit 1-- is :" + (d1--));  
           System.out.println("Now Digit 1 is :" + d1);  
           d1=this.digit1;  
           System.out.println("--Digit 1 is :" + (--d1));  
           System.out.println("Now Digit 1 is :" + d1);  
         }  
         public void shortsum()  
         {  
           short c1=5;  
           short c2=10;  
           short sum=(short)(c1+c2);  
           c1++;  
           System.out.println("C1 after increment "+c1);  
           System.out.println("Short Sum : "+sum);  
           int c3='a';  
           System.out.println(c3);  
         }  
         public void checkEven()  
         {  
           if(this.digit1!=0)  
           {  
             if(this.digit1%2==0)  
             {  
               System.out.println("Digit 1 is even");  
             }  
           }  
           else  
           {  
             System.out.println("Digit 1 is 0");  
           }  
           if(this.digit2!=0)  
           {  
             if(this.digit2%2==0)  
             {  
               System.out.println("Digit 2 is even");  
             }  
           }  
           else  
           {  
             System.out.println("Digit 2 is 0");  
           }  
         }  
         public void luck()  
         {  
           int number=0;  
           number=1+(int)(100*Math.random());  
           if(number%2==0)  
           {  
             System.out.println("You have got an even number ,"+number);  
           }  
           else  
           {  
            System.out.println("You have got an odd number ,"+number);    
           }  
         }  
         public void greatorThan()  
         {  
           int result=this.digit1>this.digit2?this.digit1:this.digit2;  
           System.out.println(result+" is Greator");  
         }  
         public void lessThan()  
         {  
           int result=this.digit1<this.digit2?this.digit1:this.digit2;  
           System.out.println(result+" is Lesser");  
         }  
         public int sumlimit(int limit)  
         {  
           int sum=0;  
           for(int i=0;i<=limit;i++)  
           {  
             sum+=i;  
           }  
           return sum;  
         }  
         public void squares()  
         {  
           for(int i=0,j=0;i<=10;i++,j++)  
           {  
             System.out.println(i*j);  
           }  
         }  
         public void factorial(long limit)  
         {  
           for(long i=1L;i<=limit;i++)  
           {  
             long number=i;  
             long factorial=1L;  
             for(long j=number;j>1;j--)  
             {  
               factorial=factorial*j;  
             }  
             System.out.println("Factorial of "+number+"is "+factorial);  
           }  
         }  
         public void primes(int limit)  
         {  
           boolean isPrime;  
           for(int i=2;i<=limit;i++)  
           {  
             isPrime=true;  
             for(int j=2;j<i;j++)  
             {  
               if(i%j==0)  
               {  
                 isPrime=false;  
                 break;  
               }  
             }  
             if(isPrime)  
             {  
               System.out.println("Caught Prime : "+i);  
             }  
           }  
         }  
         public void checkMonth(int numOfDays)  
         {  
           if(numOfDays==30)  
           {  
             System.out.println("Month is April, June, September, or November");  
           }  
           else if(numOfDays==31)  
           {  
             System.out.println("Month is January, March, May, July, August, October, or December.");  
           }  
           else if(numOfDays==28 && numOfDays==29)  
           {  
             System.out.println("Month is Feburary.");  
           }  
           else  
           {  
             assert false:"No Month Found with "+numOfDays+" days";  
           }  
         }  
         public static void main(String[] args)  
         {  
       //    //Division of -ve largest magnitude integer  
       //    calc c1=new calc(-2147483648,-1);  
       //    System.out.println(c1.divide());  
       //      
       //    //Division by zero  
       //    calc c5=new calc(25,0);  
       //    System.out.println(c5.divide());  
       //      
       //    //Increment and Decrement  
       //    calc c2 = new calc(11,14);  
       //    c2.increment();  
       //    c2.decrement();  
       //      
       //    //Short Sum  
       //    calc c3 = new calc(11,14);  
       //    c3.shortsum();  
       //      
       //    //Xor Swap  
       //    calc c4 = new calc(25,30);  
       //    c4.swap();  
           //check Even  
           calc c10=new calc(25,30);  
           c10.checkEven();  
       //    //Luck  
           calc c6=new calc(25,30);  
           c6.luck();  
       //    //Greator Than  
           calc c7=new calc(25,30);  
           c7.greatorThan();  
           c7.lessThan();  
       //    //Sum Limit  
           calc c8=new calc(25,30);  
           int sum=c8.sumlimit(20);  
           System.out.println("Sum = " + sum);  
       //    //squares  
           calc c9=new calc(25,30);  
           c9.squares();  
           c9.factorial(20L);  
           c9.primes(50);  
           c9.checkMonth(12);  
         }  
       }  
      "Class" is a keyword in Java and is reserved for defining classes it can never be used for any other purposes.There are many more reserved keywords like this.

      This Keyword
      • This keyword is used to access the data non static members of a class within a class.
      • Using this keyword we can reference class level or object level variables.
       package javaimplant.constructor;  
       public class ConstructorExample   
       {  
            private String name;  
            public ConstructorExample()   
            {  
                 System.out.println("Please also initialize name");  
            }  
            public ConstructorExample(String name) {  
                 super();  
                 this.name = name;  
                 System.out.println("Initialized with name "+name);  
            }  
            public String getName() {  
                 return name;  
            }  
            public void setName(String name) {  
                 this.name = name;  
            }  
            public static void main(String[] args) {  
                 ConstructorExample c=new ConstructorExample("Gaurav");  
            }  
       }  
      

      ddc

      No comments:

      Post a Comment