PACKAGE AND EVENT HANDLING

 

PACKAGE

 

A package is a collection of classes, interfaces and sub-packages. A sub-package in turns divides into classes, interfaces, sub-sub-packages, etc.

Learning about JAVA is nothing but learning about various packages. By default one predefined package is imported for each and every JAVA program and whose name is java.lang.*.

 Whenever we develop any java program, it may contain many number of user defined classes and user defined interfaces. If we are not using any package name to place user defined classes and interfaces, JVM will assume its own package called NONAME package.

In java we have two types of packages they are predefined or built-in or core packages and user or secondary or custom defined packages.

 

Advantage of Java Package

 

1) Java package is used to categorize the classes and interfaces so that they can be easily maintained.

 

2) Java package provides access protection.

 

3) Java package removes naming collision

 

 

PREDEFINED PACKAGES

 

Predefined packages are those which are developed by SUN micro systems and supplied as a part of JDK (Java Development Kit) to simplify the task of java programmer.

 

Lang

Util

Io

Awt

Applet

Net

 Java.io

Javax.servlet.

 

 

NOTE:

 Core packages of java starts with java. (For example: java.lang.*) and Advanced packages of java starts with javax. (For example: java.sql.*)

 

 

USER DEFINED PACKAGES

 

A user defined package is one which is developed by java programmers to simplify the task of the java programmers to keep set of classes, interfaces and sub packages which are commonly used. Any class or interface is commonly used by many java programmers that class or interface must be placed in packages.

 

STEPS for developing a PACKAGE:

 

i. Choose the appropriate package name, the package name must be a JAVA valid variable name and we showed ensure the package statement must be first executable statement.

 

ii. Choose the appropriate class name or interface name and whose modifier must be public.

 

iii. The modifier of Constructors of a class must be public.

 

iv. The modifier of the methods of class name or interface name must be public.

 

v. At any point of time we should place either a class or an interface in a package and give the file name as class name or interface name with extension .java

 

 

For example:

// Test.java

package tp;

public class Test

{

            public Test ()

            {         

                        System.out.println ("TEST - DEFAULT CONSTRUCTOR");

            }

            public void show ()

            {

                        System.out.println ("TEST - SHOW");

            }

}

 

import tp.Test;

class PackDemo

{

            public static void main (String [] args)

            {

                        Test t1=new Test ();

                        t1.show ();

            }

}

 

 

Method Overloading in java

 

If a class has multiple methods having same name but different in parameters, it is known as Method Overloading.

If we have to perform only one operation, having same name of the methods increases the readability of the program.

 

Method Overloading: changing no. of arguments

 

In this example, we have created two methods, first add() method performs addition of two numbers and second add method performs addition of three numbers.

In this example, we are creating static methods so that we don't need to create instance for calling methods.

 

class Adder

{

            static int add(int a,int b)

            {

                        return a+b;

            }

            static int add(int a,int b,int c)

            {

                        return a+b+c;

            }

}

class TestOverloading1

{

            public static void main(String[] args)

            {

                       

            System.out.println(Adder.add(11,11));                                                                      System.out.println(Adder.add(11,11,11));

            }

}

 

Method Overriding in Java

If subclass (child class) has the same method as declared in the parent class, it is known as method overriding in java.

 

Usage of Java Method Overriding

 

o Method overriding is used to provide specific implementation of a method that is already provided by its super class.

o Method overriding is used for runtime polymorphism

 

Rules for Java Method Overriding

1. method must have same name as in the parent class

2. method must have same parameter as in the parent class.

3. must be IS-A relationship (inheritance).

 

Example of method overriding

 

Class Vehicle

{

            void run()

            {

                        System.out.println("Vehicle is running");

            }

}

 

class Bike2 extends Vehicle

{

            void run()

            {

                        System.out.println("Bike is running safely");

            }

            public static void main(String args[])

            {

                        Bike2 obj = new Bike2();

                        obj.run();

            }

}

 

Output:Bike is running safely

 

 

class Bank

{

            int getRateOfInterest()

            {

                        return 0;

            }

}

 

class SBI extends Bank

{

            int getRateOfInterest()

            {

                        return 8;

            }

}

 

class ICICI extends Bank

{

            int getRateOfInterest()

            {

                        return 7;

            }

}

 

class AXIS extends Bank

{

            int getRateOfInterest()

            {         

                        return 9;

            }

}

 

class Test2

{

            public static void main(String args[])

            {

                        SBI s=new SBI();

                        ICICI i=new ICICI();

                        AXIS a=new AXIS();

            System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());             System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());

            System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());

            }

}

Output:

SBI Rate of Interest: 8

ICICI Rate of Interest: 7

AXIS Rate of Interest: 9

 

 

class Student5

{

int id;

String name;

 int age;

 

Student5(int i,String n)

{

            id = i;

            name = n;

}

Student5(int i,String n,int a)

{

             id = i;

            name = n;

            age=a;

}

void display()

{

            System.out.println(id+" "+name+" "+age);

}

public static void main(String args[])

{

            Student5 s1 = new Student5(111,"Karan");

            Student5 s2 = new Student5(222,"Aryan",25);

             s1.display();

            s2.display();

}

}

 

Abstract class in Java

 

A class that is declared with abstract keyword is known as abstract class in java. It can have abstract and non-abstract methods (method with body). It needs to be extended and its method implemented. It cannot be instantiated.

 

Example abstract class

abstract class A

{

}

 

abstract method

 

abstract void printStatus();//no body and abstract

 

Example of abstract class that has abstract method

 

abstract class Bike

{

            abstract void run();

}

class Honda4 extends Bike

{

            void run()

            {

                        System.out.println("running safely..");

            }

            public static void main(String args[])

            {

                        Honda4 obj = new Honda4();

                        obj.run();

            }

}

 

running safely..

 

 

Interface in Java

 

An interface in java is a blueprint of a class. It has static constants and abstract methods.

The interface in java is a mechanism to achieve abstraction. There can be only abstract methods in the java interface not method body. It is used to achieve abstraction and multiple inheritances in Java.

Java Interface also represents IS-A relationship. It cannot be instantiated just like abstract class.

 

There are mainly three reasons to use interface. They are given below.

 

o It is used to achieve abstraction.

o By interface, we can support the functionality of multiple inheritance.

o It can be used to achieve loose coupling.

 

//Interface declaration: by first user

interface Drawable

{

            void draw();

}

//Implementation: by second user

class Rectangle implements Drawable

{

            public void draw()

            {

                        System.out.println("drawing rectangle");

            }

}

class Circle implements Drawable

{

            public void draw()

            {

                        System.out.println("drawing circle");

            }

}

 

//Using interface: by third user

class TestInterface1

{

            public static void main(String args[])

            {

                        Drawable d=new Circle();//In real scenario, object is provided by                method e.g. getDrawable()

                         d.draw();

            }

}

 

Output:drawing circle

 

interface Printable

{

            void print();

}

 

interface Showable

{

            void show();

}

 

class A7 implements Printable,Showable

{

            public void print()

            {

                        System.out.println("Hello");

            }         

            public void show()

            {

                        System.out.println("Welcome");

            }

            public static void main(String args[])

            {

                        A7 obj = new A7();

                        obj.print();

                        obj.show();

            }

 }

Output:Hello

Welcome

 

 

interface interfacename

{

            Final variables;

            Abstract methods;

}

 

Interface intf1

{

}

Interface intf2 extends intf1

{

}

 

 

EXCEPTIONAL HANDLING

 

Whenever we develop any project in real time it should work in all circumstances (mean in any operation either in error or error free). Every technology or every programming language, if we use for implementing real time applications and if the end user commits a mistake then by default

that language or technology displays system error messages which are nothing but run time errors.

 

• Run time errors in JAVA are known as exceptions.

• System error messages are those which are unable to understand by end user or client.

• User friendly messages are those which are understandable by end user or client.

 

Exceptional handling is a mechanism of converting system error messages into user friendly messages.

 

Errors are of two types. They are compile time errors and run time errors.

 

• Compile time errors are those which are occurring because of poor understanding of the language.

 

• Run time errors are those which are occurring in a program when the user inputs invalid data.

 

The run time errors must be always converted by the JAVA programmer into user friendly messages by using the concept of exceptional handling.

 

Syntax for exceptional handling:

 

In order to handle exception in JAVA we must use the following keywords. They are try, catch, finally, throws and throw.

 

try

{

Block of statements which are to be monitored by JVM at run time (or

problematic errors);

}

catch (Type_of_exception1 object1)

{

Block of statements which provides user friendly messages;

}

catch (Type_of_exception2 object2)

{

Block of statements which provides user friendly messages;

}

.

.

.

catch (Type_of_exception3 object3)

{

Block of statements which provides user friendly messages;

}

 

finally

{

Block of statements which releases the resources;

}

 

 

Try block:

1. This is the block in which we write the block of statements which are to be monitored by JVM at run time i.e., try block must contain those statements which causes problems at run time.

2. If any exception is taking place the control will be jumped automatically to appropriate catch block.

3. If any exception is taking place in try block execution will be terminated and the rest of the statements in try block will not be executed at all and the cont

4. For every try block we must have at least one catch block. It is highly recommended to write ‘n’ number of catch’s for ‘n’ number of problematic statements.

 

Catch block:

1. This is used for providing user friendly messages by catching system error messages.

2. In the catch we must declare an object of the appropriate execution class and it will be internally referenced JVM whenever the appropriate situation taking place.

3. If we write ‘n’ number of catch’s as a part of JAVA program then only one catch will be executing at any point.

4. After executing appropriate catch block even if we use return statement in the catch block the control never goes to try block.

 

Finally block:

 

1. This is the block which is executing compulsory whether the exception is taking place or not.

2. This block contains same statements which releases the resources which are obtained in try

block (resources are opening files, opening databases, etc.).

3. Writing the finally block is optional.

 

For example:

class Ex1

{

public static void main (String [] args)

{

try

{

String s1=args[0];

String s2=args[1];

int n1=Integer.parseInt (s1);

int n2=Integer.parseInt (s2);

int n3=n1/n2;

System.out.println ("DIVISION VALUE = "+n3);

}

catch (ArithmeticException Ae)

{

System.out.println ("DONT ENTER ZERO FOR DENOMINATOR...");

}

catch (NumberFormatException Nfe)

{

System.out.println ("PASS ONLY INTEGER VALUES...");

}

catch (ArrayIndexOutOfBoundsException Aioobe)

{

System.out.println ("PASS DATA FROM COMMAND PROMPT...");

}

finally

{

System.out.println ("I AM FROM FINALLY...");

}

}

};

 

 

Throws block:

 

This is the keyword which gives an indication to the calling function to keep the

called function under try and catch blocks.

 

Syntax:

<Return type> method name (number of parameters if any) throws type of

exception1,type of exception2,………type of exception;

 

 

 

 

Inheritance in Java

Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of a parent object. It is an important part of OOPs (Object Oriented programming system).

The idea behind inheritance in Java is that you can create new classes that are built upon existing classes. When you inherit from an existing class, you can reuse methods and fields of the parent class. Moreover, you can add new methods and fields in your current class also.

Inheritance represents the IS-A relationship which is also known as a parent-child relationship.

Why use inheritance in java

Terms used in Inheritance

  • Class: A class is a group of objects which have common properties. It is a template or blueprint from which objects are created.
  • Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a derived class, extended class, or child class.
  • Super Class/Parent Class: Superclass is the class from where a subclass inherits the features. It is also called a base class or a parent class.
  • Reusability: As the name specifies, reusability is a mechanism which facilitates you to reuse the fields and methods of the existing class when you create a new class. You can use the same fields and methods already defined in the previous class.

The syntax of Java Inheritance

1.      class Subclass-name extends Superclass-name  

2.      {  

3.         //methods and fields  

4.      }  

The extends keyword indicates that you are making a new class that derives from an existing class. The meaning of "extends" is to increase the functionality.

 

 

Types of inheritance in java

On the basis of class, there can be three types of inheritance in java: single, multilevel and hierarchical.

In java programming, multiple and hybrid inheritance is supported through interface only. We will learn about interfaces later.

Note: Multiple inheritance is not supported in Java through class.

 

 

Single Inheritance Example

class Animal

{

            void eat()

            {

                        System.out.println("eating...");

            }

}

class Dog extends Animal

{

            void bark()

            {

                        System.out.println("barking...");

            }

}

class TestInheritance

{

            public static void main(String args[])

            {

                        Dog d=new Dog();

                        d.bark();

                        d.eat();

            }

}

 

Output:

 barking...

 eating...

 

 

Multilevel Inheritance Example

 

class Animal

{

            void eat()

            {

                        System.out.println("eating...");

            }

}

 

class Dog extends Animal

{

            void bark()

            {

                        System.out.println("barking...");

            }

}

 

class BabyDog extends Dog

{

            void weep()

            {

                        System.out.println("weeping...");

            }

}

 

class TestInheritance2

{

            public static void main(String args[])

            {

                        BabyDog d=new BabyDog();

                        d.weep();

                        d.bark();

                        d.eat();

            }

}

 

Output:

weeping...

barking...

 eating...

 

 

Hierarchical Inheritance Example

 

class Animal

{

            void eat()

            {

                        System.out.println("eating...");

            }

}

 

class Dog extends Animal

{

            void bark()

            {

                        System.out.println("barking...");

            }

}

 

class Cat extends Animal

{

            void meow()

            {

                        System.out.println("meowing...");

            }

}

 

class TestInheritance3

{

            public static void main(String args[])

            {

                        Cat c=new Cat();

                        c.meow();

                        c.eat();

                        //c.bark();//C.T.Error

            }

}

 

Output:

meowing...

eating...

 


 

Comments

Popular posts from this blog

OOPS CONCEPT