Monday, 29 February 2016

Java Fundamentals -2

Object and Classes

Since Java is an object oriented language, complete java language is build on classes and object. Java is also known as a strong Object oriented programming language(oops).
OOPS is a programming approach which provides solution to problems with the help of algorithms based on real world. It uses real world approach to solve a problem. So object oriented technique offers better and easy way to write program then procedural programming model such as C, ALGOL, PASCAL.

Main Features of OOPS

  • Inheritence
  • Polymorphism
  • Encapsulation
  • Abstraction
As an object oriented language Java supports all the features given above. We will discuss all these features in detail later.

Class

In Java everything is encapsulated under classes. Class is the core of Java language. Class can be defined as a template/ blueprint that describe the behaviors /states of a particular entity. A class defines new data type. Once defined this new type can be used to create object of that type. Object is an instance of class. You may also call it as physical existence of a logical template class.
A class is declared using class keyword. A class contain both data and code that operate on that data. The data or variables defined within a class are called instance variables and the code that operates on this data is known as methods.

Rules for Java Class

  • A class can have only public or default(no modifier) access specifier.
  • It can be either abstract, final or concrete (normal class).
  • It must have the class keyword, and class must be followed by a legal identifier.
  • It may optionally extend one parent class. By default, it will extend java.lang.Object.
  • It may optionally implement any number of comma-separated interfaces.
  • The class's variables and methods are declared within a set of curly braces {}.
  • Each .java source file may contain only one public class. A source file may contain any number of default visible classes.
  • Finally, the source file name must match the public class name and it must have a .java suffix.

A simple class example

Suppose, Student is a class and student's name, roll number, age will be its property. Lets see this in Java syntax
class Student.
{
 String name;
 int rollno;
 int age;
}
When a reference is made to a particular student with its property then it becomes an object, physical existence of Student class.
Student std=new Student();
After the above statement std is instance/object of Student class. Here the new keyword creates an actual physical copy of the object and assign it to the std variable. It will have physical existence and get memory in heap area. The new operator dynamically allocates memory for an object
creation of object in java

Q. How a class is initialized in java?

A Class is initialized in Java when an instance of class is created using either new operator or using reflection using class.forName(). A class is also said to be initialized when a static method of Class is invoked or a static field of Class is assigned.

Q. How would you make a copy of an entire Java object with its state?

Make that class implement Cloneable interface and call clone() method on its object. clone() method is defined in Object class which is parent of all java class by default.

Constructors in Java

A constructor is a special method that is used to initialize an object.Every class has a constructor,if we don't explicitly declare a constructor for any java class the compiler builds a default constructor for that class. A constructor does not have any return type.
A constructor has same name as the class in which it resides. Constructor in Java can not be abstract, static, final or synchronized. These modifiers are not allowed for constructor.
class Car
{
 String name ;
 String model;
 Car( )    //Constructor 
 {
  name ="";
  model="";
 }
}  

There are two types of Constructor

  • Default Constructor
  • Parameterized constructor
Each time a new object is created at least one constructor will be invoked.
Car c = new Car()       //Default constructor invoked
Car c = new Car(name); //Parameterized constructor invoked

Constructor Overloading

Like methods, a constructor can also be overloaded. Overloaded constructors are differentiated on the basis of their type of parameters or number of parameters. Constructor overloading is not much different than method overloading. In case of method overloading you have multiple methods with same name but different signature, whereas in Constructor overloading you have multiple constructor with different signature but only difference is that Constructor doesn't have return type in Java.

Q. Why do we Overload constructors ?

Constuctor overloading is done to construct object in different ways.

Example of constructor overloading

class Cricketer 
{
 String name;
 String team;
 int age;
 Cricketer ()   //default constructor.
 {
  name ="";
  team ="";
  age = 0;
 }
 Cricketer(String n, String t, int a)   //constructor overloaded
 {
  name = n;
  team = t;
  age = a;
 }
 Cricketer (Cricketer ckt)     //constructor similar to copy constructor of c++ 
 {
  name = ckt.name;
  team = ckt.team;
  age = ckt.age;
 }
 public String toString() 
 {
  return "this is " + name + " of "+team;
 }
}

Class test:
{
 public static void main (String[] args)
 {
  Cricketer c1 = new Cricketer();
  Cricketer c2 = new Cricketer("sachin", "India", 32);
  Cricketer c3 = new Cricketer(c2 );
  System.out.println(c2);
  System.out.println(c3);
  c1.name = "Virat";
  c1.team= "India";
  c1.age = 32;
  System .out. print in (c1);
 }
}
 
 output:
this is sachin of india
this is sachin of india
this is virat of india
 

Method Overriding

When a method in a sub class has same name and type signature as a method in its super class, then the method is known as overridden method. Method overriding is also referred to as runtime polymorphism. The key benefit of overriding is the abitility to define method that's specific to a particular subclass type.

Example of Method Overriding

class Animal { public void eat() { System.out.println("Generic Animal eating"); } } class Dog extends Animal { public void eat() //eat() method overriden by Dog class. { System.out.println("Dog eat meat"); } } As you can see here Dog class gives it own implementation of eat() method. Method must have same name and same type signature. NOTE : Static methods cannot be overridden because, a static method is bounded with class where as instance method is bounded with object.

Covariant return type

Since Java 5, it is possible to override a method by changing its return type. If subclass override any method by changing the return type of super class method, then the return type of overriden method must be subtype of return type declared in original method inside the super class. This is the only way by which method can be overriden by changing its return type.
Example :
class Animal { Animal myType() { return new Animal(); } } class Dog extends Animal { Dog myType() //Legal override after Java5 onward { return new Dog(); } }

Difference between Overloading and Overriding

Method OverloadingMethod Overriding
Parameter must be different and name must be same.Both name and parameter must be same.
Compile time polymorphism.Runtime polymorphism.
Increase readability of code.Increase reusability of code.
Access specifier can be changed.Access specifier most not be more restrictive than original method(can be less restrictive).
difference between overloading and overriding

Q. Can we Override static method ? Explain with reasons ?

No, we cannot override static method. Because static method is bound to class whereas method overriding is associated with object i.e at runtime.


 

instanceof operator

In Java, instanceof operator is used to check the type of an object at runtime. It is the means by which your program can obtain run-time type information about an object. instanceof operator is also important in case of casting object at runtime. instanceof operator return boolean value, if an object reference is of specified type then it return true otherwise false.

Example of instanceOf

public class Test
{
    public static void main(String[] args)
    {
      Test t= new Test();
      System.out.println(t instanceof Test);
      }
}
output true

Downcasting

downcasting in java

Example of downcasting with instanceof operator

class Parent{ }

public class Child extends Parent
{
    public void check()
    {
        System.out.println("Sucessfull Casting");
    }

    public static void show(Parent p)
    {
       if(p instanceof Child)
       {
           Child b1=(Child)p;
           b1.check();
       }
    }
    
    public static void main(String[] args)
    {
      
      Parent p=new Child();
      
      Child.show(p);
      
      }
}
Output
Sucessfull Casting

More example of instanceof operator

class Parent{}

class Child1 extends Parent{}

class Child2 extends Parent{}

class Test
{
  public static void main(String[] args)
  {
      Parent p =new Parent();
      Child1 c1 = new Child1();
      Child2 c2 = new Child2();
      
      System.out.println(c1 instanceof Parent);  //true 
      System.out.println(c2 instanceof Parent);  //true 
      System.out.println(p instanceof Child1);  //false 
      System.out.println(p instanceof Child2);  //false 
      
      p = c1;
      System.out.println(p instanceof Child1);  //true 
      System.out.println(p instanceof Child2);  //false 
      
      p = c2;
      System.out.println(p instanceof Child1);  //false 
      System.out.println(p instanceof Child2);  //true 
      
   }
    
}
Output
true
true
false
false
true
false
false
true 

this keyword

  • this keyword is used to refer to current object.
  • this is always a reference to the object on which method was invoked.
  • this can be used to invoke current class constructor.
  • this can be passed as an argument to another method.
Example :
class Box { Double width, weight, dept; Box (double w, double h, double d) { this.width = w; this.height = h; this.depth = d; } } Here the this is used to initialize member of current object.

The this is used to call overloaded constructor in java

class Car { private String name; public Car() { this("BMW"); //oveloaded constructor is called. } public Car(Stting n) { this.name=n; //member is initialized using this. } }

The this is also used to call Method of that class.

public void getName() { System.out.println("Studytonight"); } public void display() { this.getName(); System.out.println(); }

this is used to return current Object

public Car getCar() { return this; }
 

No comments:

Post a Comment