Abstract Class and Methods
Abstract Class and Methods
2
{
Private double bal;
Bankacct(double b)
{
Bal=b;
}
Void contact(double r)throws IOexception
{
Bufferedreader br=new bufferedreader(new ISR(system.in))l
S.o.p(“enter the password”);
String password=br.readLine();
If(password.equals(“xyz123”))
{
Interest in=new interest(r);//creating a inner class object inside outer class
In.calculate interest();
}
Else
{
s.o.p(“sorry ,you are not an authorized person”);
return;
}
}
Private class interest//inner class
{
Private double rate;
Interest(double r)
{
Rate=r;
}
Void calculate interest()
{
Double interest=bal*rate/100;
Bal+=interest;
S.o.p(“updated balance=”+bal);
}
}
}
Class innerclass
{
PSVM(string args[])throws IOException
{
Bankacct account=new bankacct(10000);
Account.contact(9.5);//calling outer class method
}
}
Output
Updated balance=10950
Anonymous inner class
A class that have no name is known as anonymous inner class in java.
Only single obj is created
3
In case of anonymous inner classes, we declare and instantiate them at the same time.
It should be used if you have to override method of class or interface. Java
Anonymous inner class can be created by two ways:
o Class (may be abstract or concrete).
o Interface
Abstract class
Abstract class methods can be overloaded or overridden using anonymous inner class
inside a outer class
Syntax:
AnonymousInner an_inner = new AnonymousInner() {
public void my_method() {
........
........
}
};
Ex:
abstract class AnonymousInner {
public abstract void mymethod();
}
public class Outer_class {
public static void main(String args[]) {
AnonymousInner inner = new AnonymousInner() {
public void mymethod() {
System.out.println("This is an example of anonymous inner class");
}
};
inner.mymethod();
}
}
A anonymous inner class is created but its name is decided by the complier that
extends the abstract class and implements its method
Interface
Interface methods can be overloaded or overridden using anonymous inner class
inside a outer class (implementation class)
Ex:
Interface AnonymousInner {
public void mymethod();
}
public class Outer_class implements AnonymousInner{
public static void main(String args[]) {
AnonymousInner inner = new AnonymousInner() {
public void mymethod() {
System.out.println("This is an example of interface");
}
};
inner.mymethod(); }}
4
Write a class within a method and this will be a local type.
Like local variables, the scope of the inner class is restricted within the method.
A method-local inner class can be instantiated only within the method where the
inner class is defined.
Example
public class Outerclass {
// instance method of the outer class
void my_Method() {
int num = 23;
// method-local inner class
class MethodInner_Demo {
public void print() {
System.out.println("This is method inner class "+num);
}
} // end of inner class
// Accessing the inner class
MethodInner_Demo inner = new MethodInner_Demo();
inner.print();
}
public static void main(String args[]) {
Outerclass outer = new Outerclass();
outer.my_Method();
}
}
As with class methods and variables, a static nested class is associated with its outer
class
Static attributes and methods of inner class cannot have access to the members of
outer class, Static nested class cannot access non-static (instance) data member or
method.
It cannot access non-static data members and methods. It can be accessed by outer
class name.
Need not create an object for outer class
It can access static data members of outer class including private.
Ex:
class TestOuter1{
static int data=30;
static class Inner{
void msg(){System.out.println("data is "+data);}
}
public static void main(String args[]){
TestOuter1.Inner obj=new TestOuter1.Inner();
obj.msg();
5
}}
3.Packages
Package is a directory that contains related group of classes and interfaces
Advantages
Packages hides the classes and interfaces in a separate sub directory,hence deletion is
not possible.
The classes and interfaces of a package are isolated from the classes and interfaces of
another package. This means that we can use same names for classes of two different
classes.ex:date class in java.util,java.sql
It supports reusability
Different Types of Packages
There are two different types of packages in Java. They are:
Built-in packages
User defined packages
Built-in packages
Java.lang(language)
It contains the following classes
Wrapper class-converts the data in to objects
String and string class-to handle string operations
Thread class-to create a process
Java.util(utility)
It contains collection classes
Stack
Linked list
Hash table
Vector
Arrays
Java.io-contains input and output stream classes
Java.awt-this package is used to create a graphical user interface
Javax.swing-it is a extended package of awt
Java.net-it contains interfaces and classes for network communication that supports client
server communication and sockets
Java.applet-for designing applets, the program that comes from the server and gets executed
in client machine
Java.sql-helps to connect a oracle & Sybase
Userdefined packages
Packages created by the user
User defined packages can also be implemented in other classes
To create a userdefined package
o Create a class
o Use the package that is created in another class by using import keyword
Syntax:
Package packagename;
Package packagename.subpackage;
Ex:
Step1:creating a class and a package
Package pack;
6
Public class addition
{
Private double d1,d2;
Public addition(double a,double b)
{
D1=a;
D2=b;
}
Public void sum()
{
s.o.p(“sum=”(d1+d2));
}
}
Step2:Create a obj
Pack.addition obj=new pack.addition(10,15.5);
Step3:using addition class of package pack
Class use
{
PSVM(string args[])
{
Pack.Addition obj=new pack.Addition(10,15.5);
Obj.sum();
}
}
Every time user should write the package name before the class name to overcome this
import keyword is used.
Step3:using import keyword and importing the class of package pack
Import package.Addition;
Class use
{
PSVM(string args[])
{
Addition obj=new Addition(10,15.5);
Obj.sum();
}
}
Package for interfaces
Packages for interfaces can also be created
Objects cannot be created for the interfaces
Objects can be created only for the implementation classes
Creating packages for interfaces
o Step1:create package for interface
o Step2:create a package for the implementation classes
Ex:
Step1:
Package mypack;
Public interface MyDate
{
Void show date();}
Step2:
7
Package mypack;
Import mypack.MyDate;
Import java.util.*;//importing all the utility classes
Pubic class dateImpl implements MyDate
{
Public void show date()
{
Date d=new Date();
s.o.p(d);
}
Step3:
Import mypack.DateImpl;
Class DateDisplay
{
PSVM(string args[])
{
DateImpl obj=new DateImpl();
Obj.Show date();
}
}
Creating a subpackage in a package
Subpackage can be created in a package
Syntax:
Package pack1.pack2;
To use pack2 classes and interfaces in a class import keyword is used
Ex:
Package dream.tech;
Public class sample
{
Public void show()
{
s.o.p(“welcome to dream tech”);
}
}
To include the class sample in to another class import keyword is used
Ex:
Import dream.tech.sample;
Class use
{
PSVM(string args[])
{
Sample s=new sample();
s.show();
}
}
8
Private
Protected
Default
Private Public Protected Default
Same class Yes Yes Yes Yes
Same package sub class No Yes Yes Yes
Same package non sub No Yes No Yes
class
Different package subclass No Yes Yes No
Different package non No Yes No No
subclass
Ex:
Class A & B are in a same package named pack
Class C is in a different package named mypack
Private:private-members of class Aare not available to class B or class C. This
means,member's scope is limited only to that class where it is defined. So the scope of private
specifier is class scope.
Public:public members of class A are available to class B and also classC. This means,
public members are available everywhere and their scope is global scope.
Protected:protected members of class A are available to class B, but not in class C. But if,
class C is a subclass of class A, then the protected members of class A are available to classC.
So, protected access specifier acts as public with respect to sub classes.
Default:default members of class A are accessible class B which is within the same package.
They are not available to class C. This means scope of default members is package scope.
Ex:
Package pack;
Public class A
{
Private int a=1;
Public int b=2;
Protected int c=3;
Int d=4//default
}
Package mypack;
Import pack.A;
Public class C extends class A
{
PSVM(string args[])
{
C obj=new C();
s.o.p(obj.a);
s.o.p(obj.b);
s.o.p(obj.c);
s.o.p(obj.d);
}}
Output
A is not accessible
9
B is accessible
C is accessible
D is not accessible
Class path
Class path is a environment variable that tells the java compiler where to look for the class
file to import.
Ex:c:\echo%classpath%
4.Exception handling
Errors
Compile-time errors: These are syntactical errors found in the code, fails to
compile. For example, forgetting a semicolon at the end of a Java statement, or
writing a statement without -proper syntax will result in compile-lime error
Run-time errors: These errors represent inefficiency of the computer system due to a
particular statement. For example, insufficient memory to store something or inability
microprocessor to execute some statement come under run-time errors.
Logical errors: These errors depict flaws in the logic of the program. The
programmer using a wrong formula or the design of the program itself is wrong.
Logical errors detected either by Java compiler or JVM. The programmer is solely
responsible for them.
Run time errors are known as exceptions
Types of exceptions
Checked
Unchecked
User defined
Built in exceptions
Checked exceptions
Exceptions that are detected at the compile time and throws error in run time
The programmer should either handle them or throw them without handling them.
If the exceptions that cannot be handled or thrown by the compiler then it is called run
time exceptions
Unchecked exceptions
Exceptions that are detected during run time
The programmer can write a Java program with unchecked exceptions and errors and
can compile the program.
Java compiler allows programmer to write a Java program without handling the
unchecked exceptions and errors
Ex:PSVM(string args[])throws IOException
Exception handling techniques:
When there is an exception, the user data may be - corrupted. This should be tackled by the
programmer by carefully designing the program,the following steps:
Step 1:
The programmer should observe the statements in his program where there may be a
possibility of exceptions. Such statements should be written inside a try block. A try
block looks like as follows:
Syntax:
Try
{
Statements;}
10
Even there is a possibility of the exception the program will not be terminated
JVM enters the exception details in the exception stack and jumps into the catch block
Step 2:
Exceptions that are thrown by the try statement is handled by the catch block
Catch block gives the information about the exception
The goal of the catch block is to resolve the exceptional condition and to continue
Syntax:
Catch(exceptionclass ref)
{
Statements;
Printstacktrace();//takes the exception from the stack and displays them
}
Step 3:
Finally block is executed after the try and catch block
It is executed even though there is a exception in the program that cannot be handled
by any catch
It is used for performing cleaning operations like closing the files and terminating the
threads
Syntax:
Finally
{
Statements;
}
Step 4:
If the programmer wants to throw the exception intentionally and explicitly and to
catch it
Throw keyword is used to throw the exception
It is used in the try block and in user defined exceptions
Syntax:
Throw new exception
Step 5:
If the exceptions cannot be handled ,then its thrown using throws keyword
Syntax:
Type method name(parameter-list)throws exception-list
{
//body of the method
}
Ex:PSVM(string args[])throws IOException
Handling multiple exceptions
If more than one exception could be raised by piece of code
Multiple catch blocks are used to handle multiple exceptions
Ex:
Class MultiCatch {
11
Public static void main(String args[]){
Try {
int a = args.lenght;
System.out.println(“a=”+a);
int b = 42/a;
int c [] = {1};
c [42] = 99;
}
catch (ArithmaticException e)
{
System.out.println(“Divide by 0:”+e);
}
catch(ArrayIndexofBoundsException e)
{
System.out.println(“Array index oob:” +e);
}
System.out.println(“After try/catch blocks.”);
}
}
Nested try
Try inside another try
Inner try will look for a catch ,if no catch matches then the JVM will handle the
exception
Ex:
Class Execpt {
PSVM (String args[])
{
try
{
try
{
S.O.P (“going to divide”);
Int b = 39/0;
}
Catch (ArithmeticException e)
{
S.O.P (e);
}
Try{
Int a []= new int[5];
a[5]= 4;
}
catch(ArrayIndexoutofBoundsException e)
{
12
S.O.P (e);
S.O.P (“ other statement”);
}
Catch (Exception e)
{
S.O.P (“ handled”);
}
Output
Going to divide
Other statement
Handled
Userdefined Exceptions
Exceptions created by the user are called userdefined exceptions
This exceptions are subclass to exception class which can be extended using extends
keyword
Create a constructor in exception class
Default constructor is used if the user doesn’t want to store the exception details
Parameterized constructor is used to store the exception details
To raise an exception user should create a obj to his exception class and throw it using
throw clause
Ex:
Class my exception extends exception
{
Private static int accno[]= {1001,100,1002,1004,1005};
Private static String name []={“ Raja rao”,”Rama rao”,”Subha rao”);
Private static double bal []= {10000.00,12000.00};
My exception
{
}
My excpetion (String str)
{
Super (str);
}
PSVM (String args[])
{
Try
{
S.O.P (“acc no”+”customer”+” balance”);
For ( i=0; i<5; i++)
{
S.O.P (“acc no(i)+name(i)+bal(i));
If bal([i]<1000)
{
My exception me = new myException (“balance amount Is Less”);
13
Throw me;
}}}
Catch (myException me)
{
Me.printstackTrace();
}}}
Output
Balance amount is less
Builtin exceptions
Built-in exceptions are the exceptions which are already available Java.
These exceptions, are suitable to handle certain error situations
Sr.No. Exception & Description
1 ArithmeticException
Arithmetic error, such as divide-by-zero.
2 ArrayIndexOutOfBoundsException
Array index is out-of-bounds.
3 IndexOutOfBoundsException
Some type of index is out-of-bounds.
4 NegativeArraySizeException
The array created with a negative size.
5 NullPointerException
Invalid use of a null reference.
6 NumberFormatException
Invalid conversion of a string to a numeric format.
7 SecurityException
Attempt to violate security.
8 StringIndexOutOfBounds
Attempt to index outside the bounds of a string.
9 UnsupportedOperationException
An unsupported operation was encountered.
10 ClassNotFoundException
Class not found.
11 IllegalAccessException
Access to a class is denied.
12 InterruptedException
One thread has been interrupted by another thread.
13 NoSuchFieldException
A requested field does not exist.
14 NoSuchMethodException
A requested method does not exist.
14
Wrapper class
The wrapper class in Java provides the mechanism to convert primitive into object and
object into primitive.
Autoboxing
The automatic conversion of primitive data type into its corresponding wrapper class is
known as autoboxing, for example, byte to Byte, char to Character, int to Integer, long to
Long, float to Float, boolean to Boolean, double to Double, and short to Short.
Unboxing
The automatic conversion of wrapper type into its corresponding primitive type is known as
unboxing. It is the reverse process of autoboxing
The eight classes of the java.lang package are known as wrapper classes in Java. The list of
eight wrapper classes are given below:
Boolean Boolean
Char Character
Byte Byte
Short Short
Int Integer
Long Long
Float Float
Double Double
Boolean class
The Boolean class wraps a value of the primitive type boolean in an object. Its object
contains only a single field whose type is Boolean
15
Methods Description
booleanValue() Returns a Boolean primitive for the value of this Boolean object.
equals() Returns a Boolean value true if the argument is a Boolean object that
represents the same value as this object.
getBoolean() Returns a Boolean value true if the system property name is equal to
the string "true".
Character class
The Character class generally wraps the value of all the primitive type char into an object.
Any object of the type Character may contain a single field whose type is char.
Methods
Method Description
16
character or not.
toLowerCase(char ch) Converts the character type argument to lowercase using case
mapping information obtained from the Unicode Data file.
toString() Returns a String type object which represents the value of the
character.
toString(char ch) Returns a String type object which represents the specified
character
toUpperCase(char ch) Converts the character type argument to uppercase using case
mapping information obtained from the Unicode Data file.
Byte class
The Byte class wraps a primitive byte type value in an object. Its object contains only a single
field whose type is byte.
Methods:
The java.lang.Byte class provides several different methods for converting a byte to a String
or vice versa. This class also provides other constants and methods which are useful when we
are dealing with byte.
Methods Description
17
compare() It compares the two specified byte values
equals() It is used to compare this object against the specified byte object
valueOf() Returns a Byte instance representing the specified byte or string value.
Short Class
The short class wraps a primitive short type value in an object. Its object contains only a
single field whose type is short.
Methods:
The java.lang.Short class provides several different methods for converting a short to a String
or vice versa. This class also provides other constants and methods which are useful when we
are dealing with short.
Methods Description
18
compareTo() It compares two Short objects numerically
equals() It is used to compare this object against the specified short object
reverseBytes() It returns the value fetched by reversing the order of the bytes in 2's
complement representation of the given short value.
toString() This method returns a string representation for the Short's object
19
Integer Class
The Java Integer class comes under the Java.lang.Number package. This class wraps a value
of the primitive type int in an object. An object of Integer class contains a single field of type
int value.
The Java Integer class provides several methods for converting an int to a String and a String
to an int, as well as other constants and methods dealing with an int. The various Java Integer
methods are as follows
20
7) static toBinaryString() It returns a string representation of the
String integer argument as an unsigned integer in
binary base 2.
21