Friday, January 11, 2019

OOP Concept - Programming with Java Unit 2 for B.C.A., M.C.A. and all IT Students


-------------------------------------------------------------------------------------------------------------------------
Prepared By : Uday Shah (HOD - IT)
Contact No : 7600044051
E-Mail : rupareleducation@gamil.com


Unit - 2 Inheritance Java Packages

Question 1 :: Universal class (object class)


·         There is one special object defined by the java
·         All other classes are sub classes of object
·         That's why object is the super of all other classes
·         This means that your reference variable of type object can refer to an object of any other class
·         Also array are implemented as a class variable of type of object can also refer to any array
·         Object class has member of method which means that they are available in every object
·         following is some method which are available in every object
·         1. Object Clone():: it create a new object that is the same as the object being cloan
·         2. Void Finalize():: it call before and unused object is recycle
·         3. Class getclass():: Obtain the class of an object at run time
·         4. Void notify()   ::  It resume the execution of thread waiting in the inwalk object
·         5. String to string():: It return a string that describe the object
·         All above listed are methods of object class which help to identify a class of  an object at runtime.
·         Following is an example of object class
class Abc
{
Public static void main(String args[])
{
            Integer i = new Integer(5);
            System.out.println(“Value of  I is :”+i);
            System.out.println(“Object Class is :”+i.getClass());
}
}
·         According to above example i is object of integer type which package disply using object getclass() method.
Question 2 :: Access Specifier
·         Java provide a mechanism of encapsulation
·         So it contain various elements like member variable and member function due to encaptulization you have to protect data value and its method using different types of access Specifier.
·         Access specifier is also known as Access  Control.
·         By controlling Access specifier one can prevent misuse of data member and member function.
·         And it can be possible to determine by the access specifier at the time of it’s declaration.
·         Java provide a set of Access specifier and some of them are related to inheritance or packages.
·         Following are some list of access specifier in java.
1. Public
·         When a member of a class is modified by the public specifier that member can access by any other code.
·         Public specifier achieve the higher level  of accessibility.
·         Class , Method and Fields are declare public can be access from any class in the java program.
·         Whether this classes are in the same package or in another package.
2. Private
·         When a member of a class is specified as private than that member can only be access by other member of its class. 
·         Private specifier achieve the lowers level of accessibility.
·         Private methods and fields can only be access within the same class to which the methods and fields are belongs to.
·         Private method and fields are not  visible within the sub class and are not inherited by subclass.
·         So, the private access specifier is opposite to public access specifier.
·         Using private specifier we can achieve  encaptulization and data hiding from the out side from the class.
3. Protected
·         Protected apply only when inheritance is involved.
·         It you want to allow an element to be seen outside your current package but only to classes that sub class of your class directly.
·         Then you have to declare that element as a protected.
4. Default
·         When you don’t set any access specifier for the element it will follow the default accessibility level.
·         There is no default specifier keyword class variable and method can be default access.
·         Using a default access specifier we can access class ,method or field which belongs to same package but not from outside this package.

Question 3 ::Abstract

·         Abstract class is one of the essential behaviour provide by java
·         Commonly you would like to make a class that only represent base class and do not want to create any project of this class type.
·         You can make use of abstract class to implement such a functionality in java using the modifier “Abstract”.
·         Abstract class may or may not contain Abstract Method.
·         Abstract method means a method without body
·         But if a class has at least one abstract method then class must be declare abstract.
·         If a class declare abstract then it can not be able to declare instance
·         To use abstract class you have to inherit other class provide implementation of abstract  method.
abstract class A
{
            public int sum (int a, int b)
            {
                        return  a + b;
            }
            public abstract int mul(int a, int b);
}
class B : A
{
            public int mul(int a,int b)
            {
                        return a * b;
            }
}
            class Abc
            {
                        public static void main(String args[])
                        {
                                    B b1= new B();
                                    int s1 = b1.sum(10,20);
                                    int m1 = b1.mul(10,20);
                                    System.out.pritnf(“Sum is %d and Multiply is %d “,s1,m1);
                        }
}

According to above example Class a is Abstract class and class B is inherit from class A. class A contain abstract method so class B is responsible for implement it and using main function we can access it.  
Question 4 :: Doing Inheritance

·         Inheritance is mechanism in which one class enquire all the properties  and behaviour of other parent class
·         Java also allow concept of inheritance
·         Following is the types of inheritance
1. Single
2. Multi-level
3. Hierarchical
4. Multiple
5. Hybrid

1.      Single :
·         When class is derived from only one class then it is call single inheritance


            According  to above diagram class  A is Base class and class B is Derived class so it allow to            access define property of Class A
2.      Multi Level :
            When class is a derived from another derived class it is call multi – level  inheritance.


According to above diagram class A is Base class and class B is Derived From Class A same as Class C is Derived From Class B it means class B is Child class for Class A and Prent for Class C

3.      Hierarchical  :
When more then one class derived from a single  base class then it called hierarchical inheritance.



            According to above diagram class B and Class C is derived from single base class A. It means          both the class can access the property of the same class.
4.      Multiple :
·         Multiple inheritances is feature of object oriented programming to use the concept of reusability
·         Where a class can inherit for more then one parent class the problem occurs when there exist method with the same signature.
·         In both the superclass and subclass on calling the method compiler can not determine which class method to be called and even on calling each class method get the priority
·         To overcome such a problem then introduce a new concert interface
·         Using interface we just declare a method prototype and implement this method into there sub class
·         So, now the sub-class does not require to call its parent class and all execution process are done in sub-class



·         According to above example More than one interface are implemented in there child class with same signature which id define inside the both interface And we can archive the concept of multiple inheritance
5.      Hybrid  :
·         When the class is derived from more than one form of inheritance than it is called hybrid inheritance




According to above example class A is Super Base class and class B is derived from class A same as class  D is Derived from Class B and Class C so here Class A , Class B and Class D create multiple inheritance and Class B, Class C and Class D create Multiple Inheritance.
Question : 5  Constructor in Inheritance
·         Inheritance provide concept of reusability and constructor allow initializing object at the time of creation.
·         But in case of inheritance derived class is responsible to call constructor because base class may or may not create its own object.
·         To overcome such a problem encapsulation provide a solution for this problem that whenever subclass need to refer to its immediate super class it can do by use of the keyword super.
·         Super keyword has 2 general form that is,
o   It call super class constructor.
o   It is use to access member of super class that has been hidden by member of sub class.
·         Super function must always be the first executed statement inside the sub class. Constructor and also we can pass parameter throw the super keyword to the base class constructor.

Question 6 : Method Overriding

·         If subclass has the same method as declare in the parent class it is known as method overriding in java.
·         In other word it subclass provide specific implementation of method that has been provided by one of its parent class it is know as method overriding.
·         Method overriding is use to provide a specific implementation of method that is already provided by it’s super class method overriding is used for runtime polymorphism.
·         Following is some rules for method overriding.
o   Method must have some name as in the parent class.
o   Method must have same parameter as in the parent class.
o   Must be “IS-A” Relationship.
o   Static method can not be override, Main method is static method so it can not be override.

 Question   7: Interface
·         An interface is a reference type in java. It is similar to a class. It is collection of abstract method.
·         Class implement an interface using an inheritance.
·         Along with abstract method an interface may also contain constant, default method , static method and nested type.
·         Method body exist only for default method and static method.
·         Writing an interface similar to writing a class. But class describe the attributes and behaviour of an object. And interface contains behaviour that class implement.
·         An interface is similar to class  because an interface can contain any number of method and interface is written with file.java extension
·         However an interface is different from class in a several ways. That is,
o   You can not create an instance of an interface
o   Interface does not contain any constructor
o   All of the method in interface are abstract.
o   An interface is not extended by class it is implemented by class.
o   An interface can extends multiple interface
·         Following is  syntax of declaring an interface
Access_Modifier interface interface_name
{
Abstract method ;
Abstract const variable.
·         According to above syntax interface is a keyword to define interface in program and name of the interface is must be in a valid form.
·         It contains method prototypes without implemented which is terminated by semicolon.
            interface A
            {
                        void print();
            }
class B implements A
{
            public void print()
            {
                        System.out.println(“Hello”);
            }
}
class Abc
{
public static void main(String args[])
{
            B b1 = new B();
            b1.print();
}
}
·         According to above example class A is define as abstract class and class B implement class A and its method.
Question 8 : Nested and Inner class in Java.
·         In Java just like a method, variable of a class can have another class as its member.
·         Writing a class within another is allowed in java.
·         Class written with in a class is called nested class.
·         And the class that hold the inner class is call the outer class.
·         Following is syntax to create a nested class.
class outer_class_name
{
            class  inner _classname
            {
                        Variable , Methods
            }
        }
·         According to above syntax nested class are divided into 2 types.
1.      Non static nested class.
2.      Static nested class.
·         Inner class are security mechanism in java.
·         We know a class can not be associated with the access modification private but we have the class a member of other class then inner class can be made private.
·         Creating an inner class is quite simple you need to write a class within a class.
Question 9: Final Class
·         Inheritance is the concept of reusability and it allow to access the property of base class as well as property of same class.
·         But  if we want to restrict the concept of reusability in inheritance Final class is used.
·         Once class is define as a final the class can not be inherit.
·         In a java the final modifier is use to define class as a final.
·         Following is syntax of final keyword.
Access_Modifier  final   class   class_name
{
Access_Modifier final return_type function_name (argument)
{
      Executable code…
}
}   
·         According to above syntax we can not inherit final class it means final class does not have child class.
·         It means it can’t be base class even it can not be abstract class.
·         If we try to derived a property from final class compiler through an error.
·         The second user of the final keyword is to prevent method overriding it means if the final keyword in the base class method then derived class not allow to access the same method for overriding.
·         Final keyword may be use for security reason  or may use in last class in hierarchy. For Example
class A
{
final void display()
{
            System.out.println(“Class A”);
}
}
final class B extends A
{
public void display()
{
System.out.println(“Class B”);
}
}
class Abc
{
            public static void main(String args[])
            {
                        B b1 = new B();
                        b1.display();
            }
}
·         According to above example class A contain final method so class B method can not override it. And some as  class B define final class so no one class can inherit it. So, here we prevent overloading as well as inheritance.
Question 10: Static import and Normal import.
·         Static import is new feature introduced in java.
·         The important feature allow the java program to access classes of package to access its property whereas static import feature of allow to access the static member of class without class qualification.
·         The import provide the ability to class and interface where as static import provide accessibility to static member of the class.
·         The main importance of static import is less coding require.
·         The drawback of static import is program make unreadable and difficulty to maintain.
·         Example of Static import.

import static java.lang.System.*;

class Abc
{
public static void main(String args[])
{
      out.println(“Hi”);
      System.out.println(“How Are You”);
}
}
·         According to above example here we define static import and it become program easy to write as well as also we consider that program may create a problem in maintenance.
·         System is static class so we import in a program and gain access of it,
·         Example of Normal Import Class
import java.util.*;
class Abc
{
public static void main(String args[])
{
            Random r1 = new Random();
            System.out.println(“value is :”+r1.newInt());
}
}
·         According to above example we import util package to access random value. There are number of packages which can be used as per our requirement is called normal import.

Question 11 : Introduction to java package and IMP Classes.
·         Application program interface of the context of java is collection of packages, classes and interface with there respective methods, fields and constructor.
·         Similar to user interface which facility to interaction between human and computers
·         API serve as a software program interface.
·         In java mast basic programming task are perform by the API classes and packages.
·         Which are helpful in minimize the number  of line written within peace of code
·         Following is one list of packages available in java.
1.      Java.lang
            Language support a calls that include class for primitive data type, String , math function ,    thread and execution etc.
2.      Java.util
Util means utility class. Utility package provide vector class, has table , random member etc...
3.      Java.io :
IO means input output. It provide facility for input and output of data.
4.      Java.net :
Net for networking. It means it include classes for communication with local computer as well as internet server.
5.      Java.awt :
Awt means abstract window toolkit. It is set of classes for implementing graphical user interface. They include classes for window , button , menu , list etc...
6.      Java.awt.event :
Object of this class represent high level action  event generate by awt component. Instead of representing a direct user event such as mouse and keyboard event.
7.      Java.applet:
Applet is client side programming . it allow to create an implement applet window on screen.
8.      Java.swing:
It is setoff classes for implement java.swing api such as jbutton, jframe,jmenu,jlist etc.


Question 12 : Java.lang Package class

·         Java.lang  package contain the classes that are use for fundamental to design of java programming language.
·         The java.lang class instance represent classes and interface in a running java application it has no any public constructor.
·         Java.lang also provide a different types of interface under java.lang package.
·         Thread, runable etc.. are the example of java.lang interface.
·         It support number of classes like Math class, Wrapper class, String class and stringBuffer class.
           
1.      Math Class:
The java.lang.Math class contain methods for performing a basic numeric operation such as logarithm, exponentional, square root, floor, ceiling, max, min.
Following is declaration of java.lang.Math class.
public final class Math
According to above declaration statement we can inherit the math class and fain access method of the class.

class Mathdemo
{
            public statid void main(String []args)
            {
                        double =3.4;
                        System.out.println(“Round Integer : ”+Math.int(a)+” Round Integer
                        :”+Math.round(a)+”Ceiling value:”+Math.ceil(a)+”Floor value
                        :”+Math.floor(a)+”Exponential:”+Math.exp(a));
            }
}
According to above example Math class contain all the static method so it can be implemented using its class name.
Following is some list of method in math class.
·         double sin(double a)
·         double cos(double a)
·         double tan(double a)
·         double asin(double a)
·         double acos(double a)
·         double atan(double a)
·         double log(double a)
·         double sqrt(double a)
·         double pow(double a)
·         int max(int a,int b)
·         int min(int a, int b)

            etc.. are methods of java.lang Math class
2.      Wrapper class:
·         Java use primitive type such as integer, character to hold the basic data type supported by the language they are passed by value to method and cannot be directly pass by reference.
·         Some time it is needed to create an object representation of one of the primitive type.
·         These are the collection of classes that deal with only with such object.
·         One need to wrap the primitive type into class, to satisfied this need java provide a classes that correspond to each of the primitive type.
·         The type wrapper are byte, short integer, long, character, Boolean, double, float etc.. are wide verity of classes.

3.      String class :
·         In java string is define as sequence of character but unlike many other languages that implement string as a character array.
·         In java implement string as a object of string type.
·         Java handle string  by 2 classes that is
·         String class
·         String buffer class
·         String buffer hold string that can be modify after they created
·         The string , string buffer and string buffer class are define in java.lang class.
·         The string class support several constructor that is...
·         String()
·         String (Char [])
·         String (String object) etc..
·         Are the constructor of string class which help to handle manipulation of string in java.

class stringdemo
{
      public static void main(String []args)
      {
                  String s1=new String(“Ruparel”);
                  System.out.println(“String is : “+s1);
                  String s2;
                  s2=s1+”Education”;
                  System.out.println(“String is : ”+s2);
                  char ch[]={‘J’,’U’,’N’,’A’,’G’,’A’,’D’,’H’};
                  String s3=new String(ch);
                  System.out.println(“String is : “+s3);
      }
}

According to above example String is a class which have constructor and we can define string at the time of object creation as well as we can pass character array or manual string into an object in a java.

4.      String buffer:
·         String buffer is peer class of string. String creates a string of fix length while StringBuffer create a string of flexible length.
·         That can be modify in terms of both of length and contain.
·         So, string that need modification are handle by StringBuffer.
class Abc
{
      public static void Main(String args[])
      {
                  StringBuffer s1=new StringBuffer(“Computer Department”);
                  StringBuffer s2=new StringBuffer(“Science”);
                  s1.insert(9,s2);
                  System.out.println(“String is : ”+s1);
      }
}
·         According to above example StringBuffer class allow to modify a value in a object at runtime.

Question 13 : Java.util package class

Java.util package contain the collection of framework event model, collection of classes, date & time facilities, internationalization and miscellaneous utility classes.

1.      Random class:
·         The java.util.random class instance is use to generate a random numbers.
·         This class use 48 bit value whit is modifying using liner formula import java.util.*;
class Abc
{
      public static void main(String []args)
      {
                  Random r1=new Random();
                  for(int i=1;i<=5;i++)
                  {
                              System.out.println(“value is : “+r1.nextInt());
                  }
      }
}
·         According to above example Random class is use to generate Random number it is used for real word System, gaming, puzzle etc...

2.      Date Class:
·         The java.util.date class represent a specific instance in a time with milliseconds precision. Date class encapsulate information about a specific date and time.
·         And it provide two constructor one is default and second is perameterize.
import java.util.*;
class abc
{
      public static void main(String []args)
      {
                  Date d1=new Date();
                  System.out.println(“Date is : “+d1);
      }
}
·         Date class represent a standard timezone which is available in your System with day, month, year etc...

3.      Gregorian  Calendar:
·         The abstract calendar class allow you to interrupt date and time information.
·         This class define several integar constant that are use when you get or set component of the calendar
·         The calendar class does not have not public constructor instead you may be use the static getInstance() method

import java.util.*;
class abc
{
      public static void main(String []args)
      {
                  Calendar c1=new Calendar.getInstance();
                  System.out.println(“Year is : “+c1.get(c1.year));
      }
}
·         Calendar class allow to display a number of information about date and time using its static method

4.      Vactor:
·         The vector is one the most important in all java class library
·         Because we can not expand the size of static array but we may think of vector as a dynamic array because that automatically expand as more elements are added to it
·         All vector are created with some initial capacity
·         Vector class have numbers of constructor which can be use in our program as per the requirement
class Abc
{
      Public static void main(String args[])
      {
                  Vector V1 = new Vector();
                  V1. addElement(new Integer(10));
                  V1. addElement(new Integer(20));
                  V1. addElement(new Integer(30));

                  System.out.println(“Value is : “ + v1);

                  V1.addElement (New String (“Hi...”));
                  V1.addElement (New Double (12.30));

                  System.out.println(“Value is :”+v1);
      }
}



5.      Hashtable :

·         Hashtable was part of java.util and it use to concert implementation of Directory.
·         However java is to recognize hashtable so that it also implements the map interface.
·         Hashtable is now integrated into the collection of framework. It is similar to hashmap but it is
·         Synchronize.
·         Like hashmap hashtable store key/Value pair.
·         When using hashtable you can specific an object that is used as a key and the value that you 1 want to link the key.
·         A hashtable can only store  object that override the hashcode method of a class.

            import java.util.*;
            class Abc
            {
                        public static void main(String args[])
                        {
                                    Hashtable h1=new Hashtable();
                                    h1.put(101,”Aaa”);
                                    h1.put(102,”Bbb”);
                                    h1.put(103,”Ccc”);
                                    h1.put(104,”Ddd”);
                                    for(Map.Entry m:h1.entrySet())
                                    {
                                                System.out.println(m.getHey()+” “+m.getValue());
                                    }
                        }
            }
·         Hashtable is similar to Hashmap so we can assign hashtable entry set into hashmap  and it allow to access key and value using getKey() and get Value() method.

6.      StringTokenizer:
·         StringTokenizer is the concept of java.util.StringTokenizer class allows you to break a string.
·         It is simple way to break String. The StringTokenizer class pass the data from a character input stream and generate a character input stream a sequence of Tokens.
·         A token is a group of character that represent a number or word.
·         This functionality can be useful as well as valuable if you need to build parses, compiler or any program that process character input.
·         StringTokenizer class has its own constructor which is given below.

                        StringTokenizer (String)
           
·         According to above syntax is require a string type value may be either from character array, string object or from the file.
·         Following is some general procedure to use StringTokenizer.
·         Create object for reader define how the character are to be process call nextToken () method to option the nextToken.
·         Read the Token Instance variable to determine the token type.
·         StringTokenizer class have its own method to define a token individually in a programming.
import java.util.*;
class Abc
{
      public static void main(String []args)
      {
                  StringTokenizer t1=new StringTokenizer(“My name is  mr.a”,” “);
                  While(t1.hasmoreTokens())
                  {
                              System.out.println(“Token is : ”+t1.nextToken());
                  }
      }
}
·         StringTokenizer class display string as a token in a word.

Question 14 : Creating and using user define package and sub package

·         Generally we create a class and put it into a directory and all other java classes in that directory can use the same class.
·         Sometime we may need to give the same name for more than one class and it is not possible to give 2 file with same name and extension in the same directory.
·         To overcome such a problem one can store the class in different directory each of which can have the same name.
·         Now, to identify the location where a class is store in the directory the package statement is  use.
·         Java package is group of similar type of classes, interface and sub packages.
·         Package in the java can be categorized in 2 form.
1.      Built in Package.
2.      User defines Package.
·         There are many built-in packages such as java, lang, awt, net, io, util, javax, sql etc.
·         The main purpose of java packages is used to categorize class and interface so that they can be easily maintained.
·         Java package provide access protection to compile the java to compile the java program with package statement you have to use –d option at the time of compilation in the command prompt.
·         Following is the syntax to create package and class file automatically throw command prompt.

            javac –d destination_folder filename.java

·         According to above syntax a folder with the given package name is created in the specific location and compile class file will be place in that folder.
·         While creating a package, package statement should be the first line in the source file.
·         The class under the package statement must be a public and the methods which are belongs to the class are also define public to access frequently.

package pack;
public class sum
{
            public int total(int a, int b)
            {
                        return a+b;
            }
}
import
class Abc
{
            public static void main(String []args)
            {
                        Sum s1=new Sum();
                        System.out.println(“”+s1.total(10,20));
            }
}

According to above example Package name with pack and it contain Sum class and it import in class Abc  and use in it.

Java Util Package :
Java.util package contains the collections framework, legacy collection classes, event model, date and time facilities, internationalization, and miscellaneous utility classes.

Scanner Class

  • It is a very important utility class which is used to add user defined values to the class. The class is declared as:
  • public final class Scanner
  • It extends Object
  • It implements Iterator, Closeable
  • The class methods are extended from the Object class


SimpleTimeZone

  • The class instances represent time zone to be used with the Georgians Calendar. The class is declared as:
  • public class SimpleTimeZone
  • It extends TimeZone
  • The class methods are extended from the TimeZone class.


Stack<E>

  • The class represents a data type based on the LIFO principle. The class is declared as:
  • public class Stack<E>
  • It extends Vector<E>
  • The class methods are extended from the Vector<E> class. 

Java.lang package in Java
  • Provides classes that are fundamental to the design of the Java programming language.
  • The most important classes are Object, which is the root of the class hierarchy, and Class, instances of which represent classes at run time.

Following are the Important Classes in Java.lang package :
  1. Boolean         : The Boolean class wraps a value of the primitive type Boolean
  2. in an object.
  3. Byte   : The Byte class wraps a value of primitive type byte in an object.
  4. Character :  The Character class wraps a value of the primitive type char in an object.
  5. Compiler : The Compiler class is provided to support Java-to-native-code compilers and related services.
  6. Double           : The Double class wraps a value of the primitive type double in an object.
  7. Enum : This is the common base class of all Java language enumeration types.
  8. Float  : The Float class wraps a value of primitive type float in an object.
  9. Integer          : The Integer class wraps a value of the primitive type int in an object.
  10. Long   : The Long class wraps a value of the primitive type long in an object.
  11. Number: The abstract class Number is the superclass of classes BigDecimal, BigInteger, Byte, Double, Float, Integer, Long, and Short.
  12. Object            : Class Object is the root of the class hierarchy.
  13. Package : Package objects contain version information about the implementation and specification of a Java package.
  14. String            : The String class represents character strings.
  15. StringBuffer : A thread-safe, mutable sequence of characters.
  16. StringBuilder          : A mutable sequence of characters.
  17. System: The System class contains several useful class fields and methods.
  18. Thread : A thread is a thread of execution in a program.
  19. Void    : The Void class is an uninstallable placeholder class to hold a reference to the Class object representing the Java keyword void.



:: Best Of Luck ::

Please Give Your Comment and Share it... Thank You