Thursday 30 July 2015

What is a class ?

 A class is the blueprint from which individual objects are created. The fields represent the object's state, and the methods define its interaction with the outside world. Classes are categories, and objects are items within each category.Classes are templates that are used to create objects, and to define object data types and methods.Now we focus on what is object in java

Object in java :-


An entity that has state and behavior is known as an object e.g. chair, bike, marker, pen, table, car etc.


An object has three characteristics :-

  1.    state: represents data (value) of an object.
  2.    behavior: represents the behavior (functionality) of an object such as deposit, withdraw etc.
  3.    identity: Object identity is typically implemented via a unique ID. The value of the ID is not visible to the external user. But,it is used internally by the Java Virtual Machine to identify each object uniquely.      
For Example: Car is an object. Its name is Duster, color is white etc. known as its state. It is used to ride, so riding from one place to another is its behavior.
Class is a template or blueprint from which objects are created. So object is the instance(result) of a class.

 Another Real life Example: a tree should have branches, stems and leaves. Thus, if Banyan is a tree, Banyan should have all of the characteristics of a tree, such as branches, stems and leaves. It is impossible to say that a pigeon is a tree, because the pigeon does not have branches, stems and leaves. Similarly, basic Java object properties are defined within that object’s corresponding class.

So,
Object is an instance or result of a class .

Class in java :-

A class is a group of objects that has common properties. It is a template or blueprint from which objects are created.

Syntax for declaring a class 

class <class_name>{  
    data member;  //State 
    method;            //behaviour
}  


Data member or instance variable :-
Instance variable doesn't get memory at compile time.It gets memory at runtime when object(instance) is created.That is why, it is known as instance variable.


Method or behaviour of objects :-
method is like function and used to expose behaviour of an object .Advantages of method are code reusability and code optimization .

new keyword is used to allocate memory at run time .
 Student2 s1=new Student2();  

Creating an Object :-


There are three steps when creating an object from a class:

DeclarationA variable declaration with a variable name with an object type.
InstantiationThe 'new' key word is used to create the object.
InitializationThe 'new' keyword is followed by a call to a constructor. This call initializes the new object
Now we take an example that illustrates the concepts of class as well as objects and this example maintains the records of students.

In this example, we are creating the two objects of Student class and initializing the value to these objects by invoking the insertRecord method on it. Here, we are displaying the state (data) of the objects by invoking the displayInformation method.

class Student2{  

 int rollno;  
 String name;  
  
 void insertRecord(int r, String n){  //method  
  rollno=r;  
  name=n;  
 }  
  
 void displayInformation(){System.out.println(rollno+" "+name);}//method  
  
 public static void main(String args[]){  
  Student2 s1=new Student2();  
  Student2 s2=new Student2();  
  
  s1.insertRecord(111,"Karan");  
  s2.insertRecord(222,"Aryan");  
  
  s1.displayInformation();  
  s2.displayInformation();  
  
 }  
}

Output :-

111 Karan
222  Aryan


this diagram explains concepts more clearly 


Thursday 23 April 2015

Interface In Java

Firstly ,

What is this interface in java ?



An interface in java is a blueprint of a class. It has static constants and abstract methods only.The interface in java is a mechanism to achieve fully abstraction. There can be only abstract methods in the java interface not method body. It is used to achieve fully abstraction and multiple inheritance in JavaAn interface is a collection of abstract methods. A class implements an interface, thereby inheriting the abstract methods of the interface.
An interface is not a class. Writing an interface is similar to writing a class, but they are two different concepts. A class describes the attributes and behaviors of an object. An interface contains behaviors(Abstract Methods) that a class implements.
Unless the class that implements the interface is abstract, all the methods of the interface need to be defined in the class.Since multiple inheritance is not allowed in java so interface is only way to implement multiple inheritance.

Why interface is not a class ?
An interface is similar to a class in the following ways:
  1. An interface can contain any number of methods.
  2. An interface is written in a file with a .java extension, with the name of the interface matching the name of the file.
  3. The bytecode of an interface appears in a .class file.
  4. Interfaces appear in packages, and their corresponding bytecode file must be in a directory structure that matches the package name.

  But,



  an interface is different from a class in several ways, including:
  1. You cannot instantiate an interface.
  2. An interface does not contain any constructors.
  3. All of the methods in an interface are abstract.
  4. An interface cannot contain instance fields. The only fields that can appear in an interface must be declared both static and final.
  5. An interface is not extended by a class; it is implemented by a class.
  6. An interface can extend multiple interfaces.

    So, Interface is not a class .


Properties Of An Interface :-


  • An interface is implicitly abstract. You do not need to use the abstract keyword when declaring an interface.
  • Each method in an interface is also implicitly abstract, so the abstract keyword is not needed.
  • Methods in an interface are implicitly public.


Now we understand the properties of an abstract class with diagrams 






Java compiler adds public and abstract keywords before the interface method and public,static and final keywords before data members.


Relationship between Class and Interface :-

As shown in the figure given below, a class extends another class, an interface extends another interface but a class implements an interface.





Multiple Inheritance In Java :-


If a class implements multiple interfaces, or an interface extends multiple interfaces .This is known as Multiple Inheritance 

Multiple inheritance is not supported in case of class. But it is supported in case of interface because there is no ambiguity as implementation is provided by the implementation class

A Java class can only extend one parent class. Multiple inheritance is not allowed. Interfaces are not classes, however, and an interface can extend more than one parent interface.The extends keyword is used once, and the parent interfaces are declared in a comma-separated list.

class testinterface1 implements Printable,Showable



Now let understand this with a program 

interface Printable{  
void print();  
}  
  
interface Showable{  
void print();  
}  
  
class testinterface1 implements Printable,Showable{  
  
public void print(){System.out.println("Hello");}  
  
public static void main(String args[]){  
testinterface1 obj = new testinterface1();  
obj.print();  
 }  
}

Output:-
Hello

Printable and Showable interface have same methods but its implementation is provided by class, so there is no ambiguity.

Interface Inheritance :-

When one interface extends another interface then this is called interface inheritance .Lets take an example to understand this 

interface Printable{  
void print();  
}  
interface Showable extends Printable{  
void show();  
}  
class Testinterface2 implements Showable{  
  
public void print(){System.out.println("Hello");}  
public void show(){System.out.println("Welcome");}  
  
public static void main(String args[]){  
Testinterface2 obj = new Testinterface2();  
obj.print();  
obj.show();  
 }  
}

Output Will be :-
Hello
Welcome


Some Essential Rules :-

When overriding methods defined in interfaces there are several rules to be followed:
1).   Checked exceptions should not be declared on implementation methods other than the ones declared by the interface method or subclasses of those declared by the interface method.
2).   The signature of the interface method and the same return type or subtype should be maintained when overriding the methods.
3).    An implementation class itself can be abstract and if so interface methods need not be implemented.

When implementation interfaces there are several rules:
1).   A class can implement more than one interface at a time.
2).   A class can extend only one class, but implement many interfaces.
3).   An interface can extend another interface, similarly to the way that a class can extend another class.


Sunday 19 April 2015

Abstract class in java

Abstract Class :-

Firstly i will explain you that what is an abstract class in java -

An abstract class a class that is declared abstract—it may or may not include abstract methods. Abstract classes cannot be instantiated, but they can be subclassed.
In other words,A class that is declared with abstract keyword, is known as abstract class in java. It can have abstract(method without body) and non-abstract methods (method with body).

Abstraction is a process of hiding the implementation details and showing only functionality to the user.We can achieve abstraction in two ways in java 
1. Using abstract class(0-100%)
2. Using interface(100%)

A class that is declared as abstract is known as abstract class. It needs to be extended and its method implemented. It cannot be instantiated.

Declaration :-



abstract class class_name { }

Abstract Method :-


An abstract class can include methods that contain no implementation. These are called abstract methods. The abstract method declaration must then end with a semicolon rather than a block.Abstract method can never be final and static.


Declaration :-


abstract return_type function_name ();


Lets take some examples -


// A Simple demonstration of abstract. 
abstract class A { 
abstract void callme(); 
// concrete methods are still allowed in abstract classes 
void callmetoo() { 
System.out.println("This is a concrete method."); 

}

class B extends A {  
void callme() {
  System.out.println("B's implementation of callme.");
  } 
 }

class AbstractDemo { 
 public static void main(String args[]) { 
 B b = new B(); 
 b.callme();
  b.callmetoo();  

} 

Output will be :

B's implementation of callme.
This is a concrete method.

Abstract classes cannot be used to instantiate objects, they can be used to create object references, because Java's approach to run-time polymorphism is implemented through the use of superclass references. Thus, it must be possible to create a reference to an abstract class so that it can be used to point to a subclass object. You will see this feature in the next example. 


A Different One :


abstract class Bike{  
  abstract void run();  
}  
  
class Honda4 extends Bike{  
void run(){System.out.println("running safely..");}  
  
public static void main(String args[]){  
 Bike obj = new Honda4();  
 obj.run();  
}  
}  

  1. Output will be : 
    
       running safely..
      

Important Thing About Abstract Class -:

We can not create the object of an abstract class but we can create the reference variable of an abstract class then the reference variable can be used to refer to an object of any class that is derived from abstract class .We understand this with an example 


// Using abstract methods and classes. 
abstract class Figure { 
double dim1; 
double dim2; 
Figure(double a, double b) { 
dim1 = a; 
dim2 = b; 

// area is now an abstract method 
abstract double area(); 
}
class Rectangle extends Figure { 
Rectangle(double a, double b) { 
super(a, b); 

// override area for rectangle 
double area() { 
System.out.println("Inside Area for Rectangle."); 
return dim1 * dim2; 

}
class Triangle extends Figure { 
Triangle(double a, double b) { 
super(a, b); 

// override area for right triangle 
double area() { 
System.out.println("Inside Area for Triangle."); 
return dim1 * dim2 / 2; 

}
class AbstractAreas { 
public static void main(String args[]) { 
// Figure f = new Figure(10, 10); // illegal now 
Rectangle r = new Rectangle(9, 5); 
Triangle t = new Triangle(10, 8); 
Figure figref; // this is OK, no object is created 
figref = r; 
System.out.println("Area is " + figref.area()); 
figref = t; 
System.out.println("Area is " + figref.area()); 

}

Here we see that we can not create the object of  type Figure but we can create a reference variable of type Figure.Here we created a reference variable of type Figure named figref and figref is used to refer to the objects of  Class Rectangle and Triangle .

 Points of abstract class :
  1. Abstract class contains abstract methods.
  2. Program can't instantiate an abstract class.
  3. Abstract classes contain mixture of non-abstract and abstract methods.
  4. If any class contains abstract methods then it must implements all the abstract methods of the abstract class.

 When we use Abstract class and Methods :-


Abstract methods are usually declared where two or more subclasses are expected to do a similar thing in different ways through different implementations. These subclasses extend the same Abstract class and provide different implementations for the abstract methods.

Saturday 18 April 2015

Procedure For Database Connectivity (JDBC)

JDBC Connection Consists of 6 Steps -
  •   Loading the driver
  •   Establish the connection
  •   Create a Statement object
  •   Execute the query using Statement Object
  •   Close the connection


here is the simple code for JDBC connection -


Here i am using postgresql as a database and you can use any different database which you like to use :





 import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;

public class JDBCExample {

  public static void main(String args[]) {

 System.out.println("-------- postgreSQL JDBC Connection Testing ------------");

 try {
  Class.forName("org.postgresql.Driver");
 } catch (ClassNotFoundException e) {
  System.out.println("Where is your postgreSQL JDBC Driver?");                         
  System.out.println("Failed to load Driver !");
  e.printStackTrace();
  return;
 }

 System.out.println("postgreSQL JDBC Driver Registered!");
 Connection connection = null;

 try {
  connection = DriverManager
  .getConnection("jdbc:postgresql://localhost:5432/postgres", "postgres", "p@ssw0rd");

 } catch (SQLException e) {
  System.out.println("Connection Failed! Check output console");
  e.printStackTrace();
  return;
 }

 if (connection != null) {
  System.out.println("You made it, take control your database now!");
 } else {
  System.out.println("Failed to make connection!");
 }
  }

Sunday 23 November 2014

Why Java is a platform independent language ?

Firstly we write our program (in java language) using notepad and other IDEs such as ecllipse  , netbeans . our computer does not know java language and other languages.

Then the question arises in our mind that

how computer runs our program and gives us the desired result . Answer is in our computer there is something called microprocessor which actually runs our program .But the problem is microprocessor knows only one language that is machine language ( a language consisting of 0's and 1's ) and different computers have different type of microprocessors inside them and different microprocessors understand different types of machine languages.So if we want to run our program then we have to convert our program in our computer's own machine language.Any programming language depends on microprocessors and operating system and there are many computers available in the market consists of different types of microprocessor and operating system .So the challenge is that we write our program in any language and it should run on all computers (computers with different configurations).Only there is java language that do that very easily .

Now we learn that how java does it . Firstly java compiler converts our source code into byte code and in every computer there is a program installed that is known as java virtual machine (JVM) .JVM is platform independent means computer with different microprocessor and operating system understands different machine language and JVM also understands byte code.So JVM converts bytecode into computer's own understandable machine language and computer just run it .Now we can say that JVM makes java a platform independent language.