corejava


Principles Of Object oriented programming


Object orientation is one of the programming styles or methodologies. As far as application development is concerned, following are the important object oriented features.
1.    Encapsulation
2.    Inheritance
3.    Polymorphism
Encapsulation: We develop applications mostly for data processing. Application’s data is stored in variables. Code (instructions grouped in functions) acts upon these variables to process data. “ The act of combining data and eligible code that acts upon data” is known as encapsulation. Encapsulation allows us to hide information from ineligible code of the application and there by data processing is secure.
     In an object oriented system (application), encapsulation is realized through class & object. In a class, we combine variables and eligible functions (methods in java). Total application is divided into classes. Variables and methods (functions) of one class are not accessible in other classes unless access permissions are granted. By defining a class in an application, we are defining a user defined data type. In order to store data and process it, we have to instantiate the class. An instance of a class is nothing but an object. An object holds data and code that acts upon the data. “An object oriented system is a collection of objects”.

Inheritance: Creating new classes from already existing classes through is-a relationship is known as inheritance. Already existing classes are known as super classes and newly created classes are known as a sub classes. Sub classes inherit variables and methods from super classes. Therefore, inheritance offers reusability of code. Code reusability improves productivity and consequently software can be developed at competitive prices.


Polymorphism: An object behaving differently in different situations is nothing but the object is exhibiting polymorphism. One interface, multiple forms is the key feature of polymorphism. Here, interface means method of the object. With same method name, multiple definitions will be there in a class. Each definition performs one task. With same method call we can get multiple services from the object. Polymorphism offers flexibility and extensibility of code.

Introduction to Java Programming Language


Java is an object oriented programming language from Sun Microsystems.  James Gosling has developed Java language.   Even though Java is used in many areas, programming community treats Java as a language for Internet programming (web programming).  Syntactically Java is similar to “C” programming language.  Java was first released publicly in November 1995.

Versions of Java

Versions of Java language usually correspond to the Java Development Kit (JDK).  If we want to develop, compile and execute Java programs, we need to install the Java software (JDK) in our computer.  When Java was first released, its version was 1.0.  Few additional features have been added with every new release (1.1,1.2,1.3,1.4 etc).  Even though the current version of Java is 6 (at the time writing of this book), industry is widely using J2SE 5 platform (JDK1.5 version).  Therefore, we will learn Java programming language version 1.7.

Java language Features

When Java was first created, Sun Microsystems described it with a series of buzzwords.  “Java is simple, object oriented, robust, secure, portable, high-performance, architectural, interpreted, multithreaded, distributed, dynamic language”.
Simple: - Java programming language is very easier.  It is syntactically similar to C and C++. Complex features of these languages are either simplified or totally eliminated in Java.
Object Oriented: Object orientation is a new programming paradigm (principle).  Java language has built-in support to develop applications using this methodology.
Robust: - Applications (programs) developed in java withstand against failure.  Automatic dynamic memory reclaiming and excellent exception handling mechanism contribute to this feature.
Secure:  Java is the language for the Internet.  Any malicious code can spoil the system resources in the Internet environment.  Java programs are insulated from that.  The moment any malicious code trying to influence the system resources, java programs get terminated instead of spoiling the system.  Java Runtime Environment contributes here.
Portable: Programs developed in Java can be compiled in a variety of operating environments without modifications to the source code.  Memory size of Java variables is the same in any environment.   This is another contributing factor for the portability of java applications.
High-Performance: - When compared to other interpreted languages, Java offers high performance.  Just-in-time compiler contributes towards this.
Architectural-neutral: This feature is in accordance with the Sun Microsystems slogan about java programs.  “Write once and run anywhere”.  This feature is famously known as platform independence.  A Java Program is compiled to class file(s).  These files can run on any machine with any host operating system as long as JVM is available for that OS.
Interpreted: Java programs are both compiled and interpreted.  JVM interprets the class file into machine code.
Multithreaded:  Performing more than one job at a time (concurrently) is the main goal of either multitasking or multithreading.  In case of multitasking, multiple processes are required to perform multiple jobs.  Where as, in case of multithreading a single program performs multiple jobs concurrently.  Java has built-in features to implement multithreaded applications.  Java’s contribution towards multithreading is that it has brought system level programming concept to application level.
Distributed:  Java has rich libraries for network programming and distributed computing.  As java is mainly meant for Internet based programming, it is no surprise that java is distributed.  An application is said to be distributed if the business objects are geographically dispersed in the network and communicating one another.
Dynamic: Memory allocation for application objects and libraries inclusion in programs is dynamic in java.

First Java Program

/*
This program prints “Hello, Java World” on the screen
Source Code: - one.java
*/
class ProgramOne
{
    public static void main(String args[])
    {
        System.out.println(“Hello, Java World”);
    }
}

Data Types

Java language has 8 primitive data types.
·         int
·         short
·         byte
·         long
·         float
·         double
·         char
·         boolean

int, short, byte and long are integral data types.  All these data types are used to declare variables that can store non-decimal numbers.
Data type          Memory in bytes               Range of values
 int                         4                            -21474883648 to 21474883647
 short                     2                              -32768 to 32767
 byte                      1                              -128 to 127
 long                      8           -9223372036854775808   to 9223372036854775807
Numeric values that are not integral are stored in floating-point numbers. float and double are used to store decimal numbers. If we need accuracy up to 7 digits after decimal point, we use float type. If we need accuracy up to 17 digits after decimal point, we use double type.
Floating-point literals are by default double type. If we want to specify a floating point literal, we should explicitly mention f or F. For example,
           float a=45.6F;
char primitive type variable occupy 2 bytes of memory in Java. In C & C++ languages it takes only 1 byte of memory. Java supports Unicode characters. While assigning a character literal to a variable in Java, we have to enclose it in single quotes (similar to C and C++). For example,
    char grade=’A’;
We can use arithmetic on char variables.
      grade +=1;//Earlier grade holds ‘A’ and now it holds B.
Variables of type boolean  can have only one of two values, true or false.
For example, 
 boolean  ismanager=false;//ismanager variable holds false literal now.

Operators in Java

Almost all the operators in Java are similar to that of C & C++ programming languages with very few exceptions. Their meaning and functionality is similar in Java as well.
Arithmetic Operators:          +, -, *, /, %
Relational Operators:          ==, !=, >, < , >=, <=
Assignment operators:         =, +=, -= 
Logical Operators:               !,  ||, &&
Note: - Bitwise operators in Java are similar to that of C except unsigned right shift operator >>>. It is seldom used in applications.
Variable Declaration: - In Java, variables are declared with C & C++ syntax only.
          <data type>  variablename;
Key points about variables declaration and their usage
·         We can declare variables any where within the program. The kind of restriction in ‘C’ is removed.
·         No format specifiers (unlike in ‘C’)
·         Initializing variables, or assigning values to variables is similar to that of ‘C’.
·         Variables declared in a method are known as local variables. Local variables must not be used without giving a value to them.
·         No garbage values for variables in Java.
/*
Program to add two numbers and display the sum
Source code: - add.java
*/
class AddTwoNumbers
{
   public static void main(String args[])
   {
        int n1,n2,sum;
        n1=20;
        n2=30;
        sum=n1+n2;
        System.out.println(“The sum of two numbers is:”+sum);
   }
}
Observations to be made
1.    Plus operator acts as the string concatenation operator. To separate the string and the variable “sum” we use + operator in Java.
2.    We did not prompt the user to enter data from the keyboard. Java supports that kind of programming (similar to printf & scanf in C). Without knowing exception handling & IO streams concepts we cannot do that in Java.
/*
Program to display the bigger of the two numbers
Source code: - bigger.java
*/
class BiggerNumber
{
   public static void main(String args[])
   {
        int n1=23;
       int n2=32;
      if(n1>n2)
         System.out.println(n1+ “ is bigger than “+n2);
      else
        System.out.println(n2+ “ is bigger than “+n1);
   }
}
Observations to be made
  1. Decision making in a Java program is similar to ‘C’ programming.
  2. All kinds of “if” conditions are available in Java. I.e. simple if, if else, if else ladder, nested if etc.
/*
Program to display the gross salary of an employee.
Source code: - gross.java
*/
class GrossSalary
{
   public static void main(String args[])
   {
        float basic=5000;
        float da=0.4f*basic;
       float hra=0.3f * basic;
      float gross=basic+da+hra;
     System.out.println(“Gross salary of the employee is Rs.”+gross);
   }//main
}//class
Observations to be made
1.    When we use a float literal value in a Java program, by default it is treated as double value in Java. Therefore compilation error comes. To explicitly mention that it is float value, we append f or F to the decimal number.
  1. Variables can be dynamically initialized in Java. In the above example, “gross” variable is declared and at the same time initializing it through some result of a calculation. This feature is not there in ‘C’.
Program to print numbers from 1 to 5 three times, each time using a different loop.
Source code: - loop.java
class PrintOneToFive
{
   public static void main(String args[])
   {
          for(int i=1;i<=5;i++)
                System.out.println(i);
         int i=1;
        while(i<=5)
       {
                 System.out.println(i);
                 i++;
      }
      i=1;
     do
    {               
                  System.out.println(i);
                 i++;
    } while(i<=5);
  }//main()
}//class
 Observations to be made
1.    All kinds of loops in Java are similar to that of ‘C’ as far as syntax is concerned.
2.     If we write a “for loop” in ‘C’, the loop counter will be declared before we write the loop. In Java, within the “for loop” itself we can declare it and initialize it.
3.    Variable declared within for loop is available in that loop only. Therefore we could declare a variable ‘i’ again.
/*Program that prints a multiplication table of 5 up to 10 multiples.
  Source code:- table.java */
class MultiplicationTable
{
   public static void main(String args[])
   {
         int n=5;
         int product;
        for(int i=1;i<=10;i++)
       {
            product=n*i;
           System.out.println(n+" X "+i+" = "+product);
      }             
   }//main()
}//class

Output of the program
5 X 1 = 5
5 X 2 = 10
5 X 3 = 15
5 X 4 = 20
5 X 5 = 25
5 X 6 = 30
5 X 7 = 35
5 X 8 = 40
5 X 9 = 45
5 X 10 = 50  
Q) What is the output of the following program?
   class Output
  {
   public static void main(String args[])
   {
      int i;
     System.out.println(i);
  }
}
The above program will not print any garbage value. It causes a compilation error. The variable “i” is local. We did not give proper value to it. We are trying to use it. The following compilation error is generated.
variable i might not have been initialized

Q) What is the output of the following program?
   class Output
  {
   public static void main(String args[])
   {
      int sum;
     for(int i=1;i<=5;i++)
       sum=sum+i;
    System.out.println(“The sum of first five natural numbers is:”+sum);
   }
 }
The above program also causes compilation error. The variable “sum” is declared locally in the main method. It is used in the for loop without proper value in it before first use.
The following compilation error is generated.
variable sum  might not have been initialized


Note:- All the previous examples are meant for proving that syntax wise java is similar to ‘C’. Wherever java differs also we have seen. But the purpose of Java is not yet explored. Java is mostly used in Object oriented business system development.
Object Oriented Programming in Java

Q) Write a program to represent 2 books information.
  class Book
  {
            String title;
            String author;
            float price;
            void giveDataToBook(String t,String a, float p)
            {
                     title=t;
                     author=a;
                     price=p;
            }
            void displayBookDetails()
            {
                     System.out.println("Book Title:"+title);
                     System.out.println("Author of the Book:"+author);
                     System.out.println("Book price:Rs."+price);
            }
  }  
   class ExecuteBook
  {
   public static void main(String args[])
   {
             Book b1=new Book();
             b1.giveDataToBook("Complete Reference","Herbert Schildt",310);
             System.out.println("The first book details");
             b1.displayBookDetails();
             Book b2=new Book();
             b2.giveDataToBook("Thinking in Java","Bruce Euckle",350);
             System.out.println("The second book details");
             b2.displayBookDetails();
  }//main
}//class
Output of the above program
The first book details
Book Title:Complete Reference
Author of the Book:Herbert Schildt
Book price:Rs.310.0
The second book details
Book Title:Thinking in Java
Author of the Book:Bruce Euckle
Book price:Rs.350.0
Observations to be made in the above program
1.    In the above program we defined two classes. Book class and ExecuteBook class. The first class is defined to create a user defined data type “Book”. Given question is to represent 2 books information. Programmatically they are two book objects. To create an object we need a class. Hence Book class is defined.
2.    ExecuteBook class defined only to encapsulate main(). We could have written main() in Book class also. But it is not a good programming practice to do so.
3.    In the Book class we created 3 variables. They are the properties of each book instance. They are known as instance variables in Java(data members in C++).
4.    giveDataToBook() and displayBookDetails() are the functions of Book class. In Java we should not call them functions. They are known as method. Precisely “instance methods”.
5.    In the Book class we combined variables and code(methods) that act upon the variables. I.e. we are wrapping up of data and code in a class. Therefore we say that class is the basis of encapsulation.
6.     In main method, we created 2 book objects. Syntax to create an object in Java is as follows.
                      new  classname();
         With the above syntax, an object is created. But we cannot use it later in a
         Java program. Therefore, we write the Object creation syntax to hold the
         reference  of the object so that we can use the object later.
            Book b1=new Book();// b1 is the reference of the first book object.
            Book b2=new Book();//b2 is the reference of the second book object.
7.    Using the references b1 and b2 we called 2 methods on the book objects.

Q) Write a program to represent one car information.

//Source code: Car.java
  class Car
  {
            String regno;
            String color;
            String make;
            float price;
            void giveDataToCar(String r,String c, String m,float p)
            {
                     regno=r;
                     color=c;
                     make=m;
                     price=p;
            }
            void displayCarDetails()
            {
                     System.out.println("Registration No:"+regno);
                     System.out.println("Color:"+color);
                     System.out.println("Car Make:"+make);
                     System.out.println("Price:Rs."+price);
            }
  }//Car  
   class ExecuteCar
  {
   public static void main(String args[])
   {
            Car c=new Car();
             c.giveDataToCar("AP11Q3579","white","Maruti 800 A.C",220000);
             System.out.println("Car details....");
             c.displayCarDetails();        
  }main()
}//class

Output of the program
Car details....
Registration No:AP11Q3579
Color:white
Car Make:Maruti 800 A.C
Price:Rs.220000.0

Constructors in Java
A constructor is a specialized method in Java whose name and class name is the same and is called automatically as soon the object is created. Primary purpose of a constructor is object initialization. If we don’t write any constructor in a class, Java compiler provides a zero argument constructor for the class by default. We can write our own zero argument constructor also in a class. We can have parameterized constructor also in a class.
  class Student
  {
            int regno;  String name;
             Student(int rno,String n)
            {
                     regno=rno;
                     name=n;
            }//Parameterised constructor
            Student()
            {
                     regno=1001;
                     name="Rama";
            }//zero argument constructor
            void displayStudentDetails()
            {
                     System.out.println("Student Registration No:"+regno);
                     System.out.println("Name:"+name);
                    
            }
  }  //Student class
   class ExecuteStudent
  {
       public static void main(String args[])
      {
            Student s1=new Student();
             System.out.println("First student details.....");
             s1.displayStudentDetails();
             Student s2=new Student();
             System.out.println("Second student details.....");
             s2.displayStudentDetails();
             Student s3=new Student(1003,"Ravi");
             System.out.println("Third student details.....");
             s3.displayStudentDetails();
     }//main
}//class
Program output
First student details.....
Student Registration No:1001
Name:Rama
Second student details.....
Student Registration No:1001
Name:Rama
Third student details.....
Student Registration No:1003
Name:Ravi

Observations to be made
1.     When we use zero argument constructor syntax in the object, every object is getting the same data.
2.     If we use parameterized constructor in the syntax of the object creation, we can give different data for different object.
Student s1=new Student();//zero argument constructor
Student s2=new Student();//zero argument constructor
Student s3=new Student(1003,”Ravi”);//Parameterized constructor

Q) What is the output of the following program?
class Student
  {
            int regno;
            String name;
             Student(int rno,String n)
            {
                     regno=rno;
                     name=n;
            }//Parameterised constructor
             void displayStudentDetails()
            {
                     System.out.println("Student Registration No:"+regno);
                     System.out.println("Name:"+name);
                    
            }
  }  
   class ExecuteStudent
  {
   public static void main(String args[])
   {
             Student s1=new Student();
             System.out.println("First student details.....");
             s1.displayStudentDetails();
   }
}
The above program causes compilation error as follows.
cannot resolve symbol
symbol  : constructor Student ()
location: class Student
       Student s1=new Student();
                   ^
1 error
Reason
class has no zero argument constructor that we used in the object creation syntax.
Q) What is the output of the following program?
class Student
  {
            int regno;
            String name;
             Student(int regno,String name)
            {
                     regno=regno;
                     name=name;
            }//Parameterised constructor
             void displayStudentDetails()
            {
                     System.out.println("Student Registration No:"+regno);
                     System.out.println("Name:"+name);
           }
  }  
   class ExecuteStudent
  {
   public static void main(String args[])
   {
             Student s1=new Student(100001,"David");
             System.out.println("student details.....");
             s1.displayStudentDetails();
   }
}
When we compile and execute the above program the following Output is generated.
student details.....
Student Registration No:0
Name:null
Observations to be made
1.    We supplied values to the constructor of the student class while creating the object.
2.    Because of the name clash between instance variables and parameters, we are getting the above output.
3.    To remove the name clash we have to use this keyword in the constructor.
           Student(int regno,String name)
            {
                     this.regno=regno;
                     this.name=name;
            }

Access specifiers in Java
private, protected and public are the access specifiers in Java. We apply these access specifiers to the members of the class. I.e. variables and methods of the class. If a member is not associated with these three keywords, it will have default accessibility mode in Java.
·         If a member of a class has private accessibility mode, it is accessible only from the methods of the same class.
·         If a member of a class has default accessibility mode, it is accessible to all the methods of those classes that are present in the same package.
·         If a member of a class has protected accessibility mode, it is accessible to all the methods of those classes that are present in the same package plus all child class methods.
·         If a member of a class has public accessibility mode, it is accessible to all the methods of the entire java environment.

Note: - In Java, a class can also be declared public.

Class A
{
   private int a;
   A(int a)
   {
   this.a=a;
   }
    void display()
    {
         System.out.println(“a=”+a);
    }
}
class Main
{
    public static void main(String args[])
    {
       A o=new A(10);
       o.a=30;//error
       o.display();
     }
}
The above program raises compilation error as follows.
            a has private access in A
Reason
  main method cannot directly modify “a” value. Main method is not the member of class A.
Method Overloading
If we define multiple methods with the same name with different signatures in a class, such concept is known as method overloading. We implement polymorphism in Java using this concept.
For example,
     class A
     {
           void add(int a, float b)
           {
           }           
           void add(float a, int b)
           {
           }
     }

In class A add method is overloaded.  In a class, signatures of methods with same name are said to be different if at least any one of the following criteria mismatches.
1.    number of parameters
2.    order of parameters
3.    type of parameters

Q) Example program on method overloading
  class Car
  {
            String regno; String color;  String make;  float price;
            void giveDataToCar(String r,String c, String m,float p)
            {
                     regno=r;       color=c;
                     make=m;      price=p;
            }
            void giveDataToCar(float p)
           {
               price=p;
          }
            void displayCarDetails()
            {
                     System.out.println("Registration No:"+regno);
                     System.out.println("Color:"+color);
                     System.out.println("Car Make:"+make);
                     System.out.println("Price:Rs."+price);
            }
  }//Car  
   class ExecuteCar
  {
   public static void main(String args[])
   {
              Car c=new Car();
             c.giveDataToCar("AP11Q3579","white","Maruti 800 A.C",22000);
             System.out.println("Car details....");
             c.displayCarDetails();
             c.giveDataToCar(220000);//Overloaded method call
             System.out.println("Car details....");
             c.displayCarDetails(); 
  }main()
}//class
Implementing inheritance in Java

Creating child classes from the parent classes using “extends” keyword is nothing but implementing inheritance in Java. In the following example, Vehicle is the super class and “Car” is the sub class.
                                               

Sub class inherits variables and methods of the super class. This promotes code reusability.
Q) Example program on Inheritance.
class Vehicle
{
          int wheels;
          Vehicle()
          {
                   wheels=4;
          }
          void move()
          {
                   System.out.println("Every vehicle will move this way");
          }
}//super class
class Car extends Vehicle
{

          void display()
          {
                   System.out.println("car has "+ wheels+" wheels");
          }
}//sub class
class Main
{
    public static void main(String args[])
    {
                   Car c=new Car();
                   c.move();//inherited method
                   c.display();
      }
}
Output
Every vehicle will move this way
car has 4 wheels
Q) Example program on inheritance
class Person
{
          protected int age;
          protected String name;
          void giveDataToAnyPerson(int age,String name)
          {
                   this.age=age;
                   this.name=name;
          }
          void displayPersonDetails()
        {
                   System.out.println("Age:"+age);
                   System.out.println("Name:"+name);
          }

}//super class
class Employee extends Person
{
          int empno;
           float salary;
           void giveDataToEmployee(int age,String name,int eno,float sal)
          {
                     giveDataToAnyPerson(age,name);
                    empno=eno;
                    salary=sal;
          }
          void displayEmployeeDetails()
          {
                   displayPersonDetails();
                   System.out.println("Empno:"+empno);
                   System.out.println("Salary:Rs."+salary);
          }
}//sub class 1
class Student extends Person
{
           int rollno;
           int marks;
           void giveDataToStudent(int age,String name,int rno,int m)
          {
                     giveDataToAnyPerson(age,name);
                    rollno=rno;
                    marks=m;
          }
          void displayStudentDetails()
          {
                   displayPersonDetails();
                   System.out.println("Rollno:"+rollno);
                   System.out.println("marks."+marks);
          }
}//sub class 2
class InheritanceExample
{
    public static void main(String args[])
    {
                   Employee e1=new Employee();
                   e1.giveDataToEmployee(23,"Rahim",10001,6000);
                   System.out.println("employee details");
                   e1.displayEmployeeDetails();
                   Student s1=new Student();
                   s1.giveDataToStudent(18,"Rama",1,46);
                   System.out.println("student details");
                   s1.displayStudentDetails();
       }//main()
}//class
Output of the program
employee details
Age:23
Name:Rahim
Empno:10001
Salary:Rs.6000.0
student details
Age:18
Name:Rama
Rollno:1
marks.46

Method overriding

Changing the definition of the parent class method in the sub class is known as method overriding. To implement method overriding we have to follow the given rules.
1.    super class method and sub class method signatures should be the same.
2.    Their return type should be the same.
3.    sub class method should not have weaker access privileges than that of super class method
4.    sub class method should not have more number of checked exceptions in the throws clause list.
Note: - After implementing method overriding, if we call the method on the sub class object, sub class version only be called.
Q) Example program on method overriding.
class Vehicle
{
     void move()
     {
              System.out.println("Every vehicle moves this way");
    }//overridden method
}//super class
class Car extends Vehicle
{
     void move()
     {
              System.out.println("As a car I want to move in my own way");
    }//overriding method
}
class OverridingExample
{
    public static void main(String args[])
    {
              Car c=new Car();
              c.move();      
     }
}
When we execute the above program, the following output comes.
As a car I want to move in my own way
Some times we may have to have our own functionality and also in need of the parent given functionality. In such a case, super keyword is used as follows

class Car extends Vehicle
{
     void move()
     {
                 super.move();
              System.out.println("As a car I want to move in my own way");
    }//overriding method
}

When we execute the above program, the following output comes.
Every vehicle moves this way
As a car I want to move in my own way
Note:- super keyword must be used from sub class only.
Dynamic Method Dispatch
When super class reference is referring to sub class object and method overriding is implemented, making a method call is nothing but dynamic method dispatch.
Q) Example program on dynamic method dispatch
class Vehicle
{
          void move()
          {
                   System.out.println("Every vehicle moves this way");
          }//overridden method
}
class Car extends Vehicle
{
          void move()
          {
          System.out.println("As a car I want to move in my own way");
         }//overriding method
}

class DynamicMethodDispatch
{
    public static void main(String args[])
    {
                   Vehicle v=new Car();
                   v.move();      
     }
}
When the above program is executed the following output comes.
As a car I want to move in my own way
Observations to be made
1.    Reference is of type super class
2.    “v” is referring to sub class object
3.    Using the super class reference, the call is made.


Constructors in inheritance
Whenever sub class object is created, super class zero argument constructor is executed first and then sub class one executed. Whenever the sub class object is created, its constructor is called first. From there an implicit call is made to the super class zero argument constructor. If it is found, it will be executed. If not found, error will be reported. Sub class object creation fails.
Q) What is the output of the following program ?
class A
{
          A()
          {
                   System.out.println("super cnstr");
          }
}
class B extends A
{
          B()
          {
              System.out.println("sub cnstr");
          }
}
class C
{
    public static void main(String args[])
    {
                   B b=new B();     
     }
}

When the above program is executed, the following output is displayed.
super cnstr
sub cnstr


Q) What is the output of the following program?
class A
{
          A(int a)
          {
                   System.out.println("super cnstr");
          }
}
class B extends A
{
          B()
          {
                   System.out.println("sub cnstr");
          }
}
class C
{
    public static void main(String args[])
    {
          B b=new B();     
     }
}
The above program generates compilation error. Object creation fails at compilation level itself. The reason is, in the super class there is no zero argument constructor available.
To overcome this problem we have 2 options. Either defining the zero argument constructor in the super class or to make an explicit call from the sub class constructor to the super class constructor as follows.
          B()
          {
                   super(10);
                   System.out.println("sub cnstr");
          }
Note:- Call to the super class constructor should be the first statement in the sub class constructor.


Modifiers in Java

static, abstract and final are three important modifiers in Java. When we apply them to the members of a class their meaning will be changed.
static variables
These are used to represent the whole class level information rather than individual object information. Per class only one copy of static variables is created. A static variable can be referred by class name.
Q) Example program on static variable usage.
class Employee
{
     static int count;
     Employee()
     {
              count++;
              System.out.println("Employee appointed");
     }
     void getEmpCount()
     {
              System.out.println("No. of employees appointed:"+count);
     }
}
class StaticExample
{
    public static void main(String args[])
    {
              System.out.println("No. of employees appointed:"+Employee.count);
              Employee e1=new Employee();
              e1.getEmpCount();
              Employee e2=new Employee();
              e2.getEmpCount();
     }//main()
}//class
When the program is executed the following output comes.
No. of employees appointed:0
Employee appointed
No. of employees appointed:1
Employee appointed
No. of employees appointed:2

static methods
If a method of a class is declared static, it becomes the class method. We can call that method directly on the class.
    ClassName.method();
In the previous example, if “count” variable is made private, we cannot access it directly from main method. In such a case, getEmpCount() should have been made static.
Q) Static method example
class Employee
{
     private static int count;
     Employee()
     {
              count++;
              System.out.println("Employee appointed");
     }
     static void getEmpCount()
     {
              System.out.println("No. of employees appointed:"+count);
     }//static method definition
}
class StaticExample
{
    public static void main(String args[])
    {
              Employee.getEmpCount();//static method call
              Employee e1=new Employee();
              e1.getEmpCount();
              Employee e2=new Employee();
              e2.getEmpCount();
     }
}
Note:- Without a reference we should not reference an instance variable or an instance method in a static  method. If object is available, a static method can be called using object reference also.
final modifier
We can associate this modifier with variables, methods and classes also.
final variables: - We declare constants in java using final. Final variables must be defined. Their value cannot be changed once they are defined.
For example,
    class  A
    {
      final int a=10;
    }
final methods:-  If a method is declared final, it can be inherited but it cannot be overridden.
For example,
  class A
  {
       final void x()  {  }
}
class B extends A
{
   void y()
   {
       x();//allowed because final method is inherited
   }
  void (x){}//not allowed because final methods cannot be overridden.         
}
final class: -  If a class is declared final, it cannot be inherited. In a hierarchy of classes, the most specialized class can generally be declared “final” if we want.
For example,
  final class A{}  class B extends A{} // not allowed
abstract modifier
abstract modifier is associated with methods and classes only. If a class is declared abstract, it has all the features of a non-abstract class except in one thing. We cannot create the instance of an abstract class. An abstract method has only declaration but no definition. Declaring a method abstract means that we are forcing all the sub classes to override (implement) that method.
For example,
   abstract class Diagram
   {
          abstract void draw();
   }
If a method is declared abstract, the class in which it is declared also must declared abstract. In a hierarchy of classes the most generalized class is generally declared abstract. Every sub class of an abstract class must implement all the abstract methods of its super class.
For example,
   class Square extends Diagram
   {
      void draw()
      {
          System.out.println(“square is drawn”);
      }
   }
   class Rectangle extends Diagram
   {
        void drawSquare()
        {
        } 
   }
When we compile the source code, Compiler reports an error saying that “Rectangle” class should be declared abstract. It is inheriting from an abstract class “Diagram”, but not overriding the draw() method. To rectify the error, either we have to declare the Rectangle class abstract OR implement the draw() method.

Note: - We cannot declare a variable as abstract in Java.
INTERFACES

An interface is a named collection of method declarations (without implementations).
An interface can have only abstract methods. It also can have constants (only) also.
For example,
  interface I1
  {
       public static final int VALUE=10;
       public abstract void x();
  }
In the above example, VALUE is the constant. We need not use the 3 keywords for it. It is implicitly public, static and final. For the method x() public and abstract are implicitly available.
A class can inherit an interface. For example,
interface I2{}
class A implements I2
{
}
In the above example, I2 is the parent and A is the sub class. If a class is inheriting from an interface, the class must implement all the abstract methods of the interface. Otherwise, the class also should be declared abstract.
All the members of an interface are by default public. A class can inherit from any number of interfaces.
For example,
   class A implements I1, I2 {}
An interface reference can be created. But its instance cannot be created.
Q) Example program on interface.
interface I1
{
     void y();
}
class A implements I1
{
   public void y()
  {
  System.out.println(“ Some functionality”);
   }
}//sub class
class InterfaceExample
{
   public static void main(String args[])
   {
         I1 i=new A();
         i.y();
    }
}
Observations to be made
1.    I1 is acting as the parent type of class A.
2.    Parent type reference can refer to the sub class object.
3.    In the interface I1, y() is public and abstract. Therefore, we must override it in the sub class A.
One interface can inherit from another interface. Here, extends keyword is used. If a class is implementing sub interface, the class should implement all the methods of super interface as well as the sub interface.
interface I1
{
   void x();
}
interface I2 extends I1
{
   void y();
}
class A implements I2
{
   public void x()
   {        //some implementation   }
   void y()
   {        //some implementation
   }
}//sub class
PACKAGES
A package is a collection of related class files. To make classes easier to locate and use, to control access and to control class-naming conflicts, we bundle collection of related classes and interfaces into packages. Packages are classified into standard and user defined. lang, util, io, net, awt, applet etc. are some of the important standard packages. In these packages library class files are stored. For every Java program lang package is automatically available. We have to include any other package explicitly into the Java program if we need any library class file from that package. For example, in order to include io package we use the import statement import java.io.*;
We can create our own packages known as user defined packages. We group our own application class files into the user-defined package. In order to create our own package, in the java program we have to use the package statement as the first statement.
For example, package mypack;
Q) Example program that creates a user defined package.
  package mypack;
  public class A
  {
          public void x()
           {
                System.out.println(“user defined package example”);
            }
   }
Now we compile the program as follows. javac –d . A.java  
With the above command, mypack directory(package) is created in the current working directory. A.class file is stored in mypack. In order to use the user defined package, we need to set the classpath to the directory in which mypack is stored. Then import the mypack and make use of class A and its method.
import mypack.A;
class C{
   public static void main(String args[]){    
       A a=new A(); a.x();
    }
}
Arrays in Java

An array is a collection of homogeneous elements referred by the same name. An array is also known as sub-scripted variable. An array is created in Java with the following syntax.
    datatype  arrayriable[]=new datatype[size];
For example, 
int a[]=new int[10];
The above syntax creates an integer array of size 10. In Java, arrays are internally represented as objects. Every array has property known as length that gives the size of the array.
Q) Write a program to store first 5 natural numbers in an array and display them.
/*
source code:- ArrayExample.java
*/
class ArrayExample
{
          public static void main(String[] args)
          {
                   int arr[]=new int[5];
                   for(int i=0;i<arr.length;i++)
                             arr[i]=i+1;
                   System.out.println("elemtns of the array..........");
                   for(int i=0;i<arr.length;i++)
                             System.out.println(arr[i]);
          }
}
Program output
elemnts of the array..........
1
2
3
4
5


User defined arrays
Whenever an array of user defined data type is created, an array of objects is not created. Instead, an array of references is created.
For example, Student s[]=new Student[5];
Q) Example program on user defined arrays
class Student
{
          int rollno;
          Student(int rno)
          {
                   rollno=rno;
         }
          void display()
          {
                   System.out.println("Rollno:"+rollno);
           }
}
class  ArrayOfObjects
{
          public static void main(String[] args)
          {
                   Student s[]=new Student[4];;
                   for(int i=0;i<s.length;i++)
                             s[i]=new Student(i+1);
                   System.out.println("Objects are...");
                     for(int i=0;i<s.length;i++)
                      s[i].display();
          }
}
Objects are...
Rollno:1
Rollno:2
Rollno:3
Rollno:4


Leave a Reply