Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
39 views23 pages

Java Unit2

Download as docx, pdf, or txt
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 23

STRINGS IN JAVA

 Strings are widely used in Java programming


 Strings are sequence of characters
 In Java, Strings are treated as objects

Creating Strings
1. Using String literal
Eg: String str1 = “Hello”;
2. Using another String object
Eg: String str2 = new String(str1);
3. Using new keyword
String str3 = new String(“Java”);
4. Using + operator (Concatenation)
Eg: String str4 = str1+str2;

Java String class methods


The java.lang.String class provides many useful methods to perform operations on sequence of char
values.
Method Description

char charAt(int index) returns char value for the particular index

int length() returns string length

static String format(String format, Object... returns formatted string


args)

static String format(Locale l, String format, returns formatted string with given locale
Object... args)

String substring(int beginIndex) returns substring for given begin index

String substring(int beginIndex, int returns substring for given begin index and end
endIndex) index

boolean contains(CharSequence s) returns true or false after matching the sequence of


char value

static String join(CharSequence delimiter, returns a joined string


CharSequence... elements)

static String join(CharSequence delimiter, returns a joined string


Iterable<? extends CharSequence>
elements)

boolean equals(Object another) checks the equality of string with object

boolean isEmpty() checks if string is empty

String concat(String str) concatinates specified string

String replace(char old, char new) replaces all occurrences of specified char value

String replace(CharSequence old, replaces all occurrences of specified CharSequence


CharSequence new)
static String equalsIgnoreCase(String compares another string. It doesn't check case.
another)

String[] split(String regex) returns splitted string matching regex

String[] split(String regex, int limit) returns splitted string matching regex and limit

String intern() returns interned string

int indexOf(int ch) returns specified char value index

int indexOf(int ch, int fromIndex) returns specified char value index starting with
given index

int indexOf(String substring) returns specified substring index

int indexOf(String substring, int fromIndex) returns specified substring index starting with given
index

String toLowerCase() returns string in lowercase.

String toLowerCase(Locale l) returns string in lowercase using specified locale.

String toUpperCase() returns string in uppercase.

String toUpperCase(Locale l) returns string in uppercase using specified locale.

String trim() removes beginning and ending spaces of this string.

static String valueOf(int value) converts given type into string. It is overloaded.

STRING BUFFER CLASS


StringBuffer class is used to create a mutable string object i.e its state can be changed after it is created. It
represents growable and writable character sequence. As we know that String objects are immutable, so if
we do a lot of changes with String objects, we will end up with a lot of memory leak.

So StringBuffer class is used when we have to make lot of modifications to our string. It is also thread
safe i.e multiple threads cannot access it simultaneously. StringBuffer defines 4 constructors. They are,

 StringBuffer ( )
 StringBuffer ( int size )
 StringBuffer ( String str )
 StringBuffer ( charSequence [ ]ch )

StringBuffer() creates an empty string buffer and reserves room for 16 characters.
StringBuffer(int size) creates an empty string and takes an integer argument to set capacity of the buffer.
Eg:
class Test {
public static void main(String args[])
{
String str = "study";
str.concat("tonight");
System.out.println(str); // Output: study

StringBuffer strB = new StringBuffer("study");


strB.append("tonight");
System.out.println(strB); // Output: studytonight
}
}

String objects are immutable objects. Hence, if we concatenate on the same String object, it won't be
altered(Output: study). But StringBuffer creates mutable objects. Hence, it can be altered(Output:
studytonight).

Important methods of StringBuffer class

Modifier and Method Description


Type

public append(String s) is used to append the specified string with this string. The
synchronized append() method is overloaded like append(char),
StringBuffer append(boolean), append(int), append(float),
append(double) etc.

public insert(int offset, is used to insert the specified string with this string at the
synchronized String s) specified position. The insert() method is overloaded like
StringBuffer insert(int, char), insert(int, boolean), insert(int, int),
insert(int, float), insert(int, double) etc.

public replace(int is used to replace the string from specified startIndex and
synchronized startIndex, int endIndex.
StringBuffer endIndex, String str)

public delete(int startIndex, is used to delete the string from specified startIndex and
synchronized int endIndex) endIndex.
StringBuffer

public reverse() is used to reverse the string.


synchronized
StringBuffer

public int capacity() is used to return the current capacity.

public void ensureCapacity(int is used to ensure the capacity at least equal to the given
minimumCapacity) minimum.

public char charAt(int index) is used to return the character at the specified position.

public int length() is used to return the length of the string i.e. total number of
characters.

public String substring(int is used to return the substring from the specified
beginIndex) beginIndex.

public String substring(int is used to return the substring from the specified
beginIndex, int beginIndex and endIndex.
endIndex)
VECTOR
Vector implements a dynamic array. It is similar to ArrayList, but with two differences −
 Vector is synchronized.
 Vector contains many legacy methods that are not part of the collections framework.
Constructors
 Vector( ) : This constructor creates a default vector, which has an initial size of 10.
 Vector(int size) : This constructor accepts an argument that equals to the required size, and creates
a vector whose initial capacity is specified by size.
 Vector(int size, int incr) : This constructor creates a vector whose initial capacity is specified by
size and whose increment is specified by incr. The increment specifies the number of elements to
allocate each time that a vector is resized upward.
 Vector(Collection c) : This constructor creates a vector that contains the elements of collection c.
Methods in Vector class

void add(int index, Object element)


1
Inserts the specified element at the specified position in this Vector.

boolean add(Object o)
2
Appends the specified element to the end of this Vector.

boolean addAll(Collection c)
3 Appends all of the elements in the specified Collection to the end of this Vector, in the order
that they are returned by the specified Collection's Iterator.

boolean addAll(int index, Collection c)


4
Inserts all of the elements in in the specified Collection into this Vector at the specified position.

void addElement(Object obj)


5
Adds the specified component to the end of this vector, increasing its size by one.

int capacity()
6
Returns the current capacity of this vector.

void clear()
7
Removes all of the elements from this vector.

Object clone()
8
Returns a clone of this vector.

boolean contains(Object elem)


9
Tests if the specified object is a component in this vector.

boolean containsAll(Collection c)
10
Returns true if this vector contains all of the elements in the specified Collection.

void copyInto(Object[] anArray)


11
Copies the components of this vector into the specified array.

Object elementAt(int index)


12
Returns the component at the specified index.

Enumeration elements()
13
Returns an enumeration of the components of this vector.

14 void ensureCapacity(int minCapacity)


Increases the capacity of this vector, if necessary, to ensure that it can hold at least the number
of components specified by the minimum capacity argument.

boolean equals(Object o)
15
Compares the specified Object with this vector for equality.

Object firstElement()
16
Returns the first component (the item at index 0) of this vector.

Object get(int index)


17
Returns the element at the specified position in this vector.

int hashCode()
18
Returns the hash code value for this vector.

int indexOf(Object elem)


19 Searches for the first occurence of the given argument, testing for equality using the equals
method.

int indexOf(Object elem, int index)


20 Searches for the first occurence of the given argument, beginning the search at index, and
testing for equality using the equals method.

void insertElementAt(Object obj, int index)


21
Inserts the specified object as a component in this vector at the specified index.

boolean isEmpty()
22
Tests if this vector has no components.

Object lastElement()
23
Returns the last component of the vector.

int lastIndexOf(Object elem)


24
Returns the index of the last occurrence of the specified object in this vector.

int lastIndexOf(Object elem, int index)


25 Searches backwards for the specified object, starting from the specified index, and returns an
index to it.

Object remove(int index)


26
Removes the element at the specified position in this vector.

boolean remove(Object o)
27 Removes the first occurrence of the specified element in this vector, If the vector does not
contain the element, it is unchanged.

boolean removeAll(Collection c)
28
Removes from this vector all of its elements that are contained in the specified Collection.

void removeAllElements()
29
Removes all components from this vector and sets its size to zero.

boolean removeElement(Object obj)


30
Removes the first (lowest-indexed) occurrence of the argument from this vector.

31 void removeElementAt(int index)


removeElementAt(int index).

protected void removeRange(int fromIndex, int toIndex)


32 Removes from this List all of the elements whose index is between fromIndex, inclusive and
toIndex, exclusive.

boolean retainAll(Collection c)
33
Retains only the elements in this vector that are contained in the specified Collection.

Object set(int index, Object element)


34
Replaces the element at the specified position in this vector with the specified element.

void setElementAt(Object obj, int index)


35
Sets the component at the specified index of this vector to be the specified object.

void setSize(int newSize)


36
Sets the size of this vector.

int size()
37
Returns the number of components in this vector.

List subList(int fromIndex, int toIndex)


38
Returns a view of the portion of this List between fromIndex, inclusive, and toIndex, exclusive.

Object[] toArray()
39
Returns an array containing all of the elements in this vector in the correct order.

Object[] toArray(Object[] a)
40 Returns an array containing all of the elements in this vector in the correct order; the runtime
type of the returned array is that of the specified array.

String toString()
41 Returns a string representation of this vector, containing the String representation of each
element.

void trimToSize()
42
Trims the capacity of this vector to be the vector's current size.

Eg:
import java.util.*;
public class VectorDemo {

public static void main(String args[]) {


// initial size is 3, increment is 2
Vector v = new Vector(3, 2);
System.out.println("Initial size: " + v.size());
System.out.println("Initial capacity: " + v.capacity());

v.addElement(new Integer(1));
v.addElement(new Integer(2));
v.addElement(new Integer(3));
v.addElement(new Integer(4));
System.out.println("Capacity after four additions: " + v.capacity());

v.addElement(new Double(5.45));
System.out.println("Current capacity: " + v.capacity());

v.addElement(new Double(6.08));
v.addElement(new Integer(7));
System.out.println("Current capacity: " + v.capacity());

v.addElement(new Float(9.4));
v.addElement(new Integer(10));
System.out.println("Current capacity: " + v.capacity());

v.addElement(new Integer(11));
v.addElement(new Integer(12));
System.out.println("First element: " + (Integer)v.firstElement());
System.out.println("Last element: " + (Integer)v.lastElement());

if(v.contains(new Integer(3)))
System.out.println("Vector contains 3.");

// enumerate the elements in the vector.


Enumeration vEnum = v.elements();
System.out.println("\nElements in vector:");

while(vEnum.hasMoreElements())
System.out.print(vEnum.nextElement() + " ");
System.out.println();
}
}

Output
Initial size: 0
Initial capacity: 3
Capacity after four additions: 5
Current capacity: 5
Current capacity: 7
Current capacity: 9
First element: 1
Last element: 12
Vector contains 3.

Elements in vector:
1 2 3 4 5.45 6.08 7 9.4 10 11 12

JAVA - METHODS

A Java method is a collection of statements that are grouped together to perform an operation.
Creating Method

Syntax
public static int methodName(int a, int b) {
// body
}
Here,
 public static − modifier
 int − return type
 methodName − name of the method
 a, b − formal parameters
 int a, int b − list of parameters

Method definition consists of a method header and a method body

Syntax
modifier returnType nameOfMethod (Parameter List) {
// method body
}
The syntax shown above includes
 modifier − It defines the access type of the method and it is optional to use.
 returnType − Method may return a value.
 nameOfMethod − This is the method name. The method signature consists of the method name
and the parameter list.
 Parameter List − The list of parameters, it is the type, order, and number of parameters of a
method. These are optional, method may contain zero parameters.
 method body − The method body defines what the method does with the statements.
Example

public static int minFunction(int n1, int n2) {


int min;
if (n1 > n2)
min = n2;
else
min = n1;

return min;
}

Method Calling
For using a method, it should be called. There are two ways in which a method is called i.e., method
returns a value or returning nothing (no return value).

The process of method calling is simple. When a program invokes a method, the program control gets
transferred to the called method. This called method then returns control to the caller in two conditions,
when −
 the return statement is executed.
 it reaches the method ending closing brace.

Example
public class ExampleMinNumber {

public static void main(String[] args) {


int a = 11;
int b = 6;
int c = minFunction(a, b);
System.out.println("Minimum Value = " + c);
}

/** returns the minimum of two numbers */


public static int minFunction(int n1, int n2) {
int min;
if (n1 > n2)
min = n2;
else
min = n1;

return min;
}
}

The void keyword allows us to create methods which do not return a value.
Method Overloading
When a class has two or more methods by the same name but different parameters, it is known as method
overloading. It is different from overriding. In overriding, a method has the same method name, type,
number of parameters, etc.
Example
public class ExampleOverloading {
public static void main(String[] args) {
int a = 11;
int b = 6;
double c = 7.3;
double d = 9.4;
int result1 = minFunction(a, b);
// same function name with different parameters
double result2 = minFunction(c, d);
System.out.println("Minimum Value = " + result1);
System.out.println("Minimum Value = " + result2);
}
// for integer
public static int minFunction(int n1, int n2) {
int min;
if (n1 > n2)
min = n2;
else
min = n1;
return min;
}
// for double
public static double minFunction(double n1, double n2) {
double min;
if (n1 > n2)
min = n2;
else
min = n1;
return min;
}
}

The Constructors
A constructor initializes an object when it is created. It has the same name as its class and is syntactically
similar to a method. However, constructors have no explicit return type.
Example
// A simple constructor.
class MyClass {
int x;
// Following is the constructor
MyClass() {
x = 10;
}
}
public class ConsDemo {
public static void main(String args[]) {
MyClass t1 = new MyClass();
MyClass t2 = new MyClass();
System.out.println(t1.x + " " + t2.x);
}
}
Parameterized Constructor
Example
// A simple constructor.
class MyClass {
int x;
// Following is the constructor
MyClass(int i ) {
x = i;
}
}
public class ConsDemo {
public static void main(String args[]) {
MyClass t1 = new MyClass( 10 );
MyClass t2 = new MyClass( 20 );
System.out.println(t1.x + " " + t2.x);
}
}

OBJECT ORIENTED FEATURES


Object-oriented programming (OOP) is at the core of Java. Object oriented programming is a
programming that associates data structures with a set of operators which act upon it. OOP uses object as
its fundamental building blocks.
Various elements of OOP are

 Object
 Class
 Data abstraction and encapsulation
 Inheritance
 Polymorphism
 Dynamic binding
 Message passing

Object

Objects are the basic run time entities in an object oriented system. They may represent a person, a place
or any data item. Objects contain data and code that manipulates that data.

Class

The entire set of data and code of an object that can be made a user defined data type with the help of a
class. A class is a collection of objects of type class.

Data Abstraction
The technique of creating new data types providing higher level view of the data that are well suited to an
application to be programmed is known as data abstraction.

Data Encapsulation

The wrapping up of data and functions into a single unit called class is known as data encapsulation.

Data Hiding

The insulation of the data from direct access by the program is called data hiding or information hiding.

Inheritance

Inheritance is the process by which objects of one class acquire the properties of objects of another class.
The concept of inheritance provides the idea of reusability. This means that we can add additional
features to an existing class without modifying it. Derivation involves the creation of new classes (derived
class) from the existing ones (base class).

Polymorphism

Polymorphism means the ability to take more than one form. There are two types of
polymorphism.

Compile Time Polymorphism – Polymorphism is exhibited during compilation of source code.


Eg: Function overloading, Operator Overloading.

Runtime Polymorphism – Polymorphism is exhibited during runtime. Eg: Virtual Functions,


Templates.

Dynamic Binding

Binding refers to the linking of a procedure call to the code to be executed in response to the call.
Dynamic binding also known as late binding means that the code associated with a given procedure call is
not known until the time of call at run time.

Message Passing

Process of invoking an operation on an object is known as message passing. Execution of actual method
is the response.

CLASSES
A class is a user defined data type. Once defined, this new type can be used to create objects of that type.
Thus, a class is a template for an object, and an object is an instance of a class. A class is declared by use
of the class keyword.
Syntax
class classname {
type instance-variable1;
type instance-variable2;
// ...
type instance-variableN;
type methodname1(parameter-list) {
// body of method
}
type methodname2(parameter-list) {
// body of method
}
// ...
type methodnameN(parameter-list) {
// body of method
}
}
The data, or variables, defined within a class are called instance variables. The code is contained within
methods. Collectively, the methods and variables defined within a class are called members of the class.
Java classes do not need to have a main( ) method.
Eg:
class Box {
double width;
double height;
double depth;
}
To actually create a Box object, we will use a statement like the following:
Box mybox = new Box(); // create a Box object called mybox

Every Box object will contain its own copies of the instance variables width, height, and depth. To access
these variables, you will use the dot (.) operator. The dot operator links the name of the object with the
name of an instance variable. For example, to assign the width variable of mybox the value 100, you
would use the following statement:
mybox.width = 100;

INNER CLASSES
It is possible to place a class definition within another class definition. This is called an inner class. The
inner class is a valuable feature because it allows you to group classes that logically belong together and
to control the visibility of one within the other.
Eg:
public class Parcel1 {
class Contents { // inner class
private int i = 11;
public int value() { return i; }
}
class Destination {// inner class
private String label;
Destination(String whereTo) {
label = whereTo;
}
String readLabel() { return label; }
}
public void ship(String dest) {
Contents c = new Contents();
Destination d = new Destination(dest);
System.out.println(d.readLabel());
}
public static void main(String[] args) {
Parcel1 p = new Parcel1();
p.ship("Tanzania");
}
}

ABSTRACT CLASS
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. A method that is declared as abstract and does not have implementation is known as
abstract method.
Example
In this example, Shape is the abstract class, its implementation is provided by the Rectangle and Circle
classes.

abstract class Shape


{
abstract void draw();
}
//In real scenario, implementation is provided by others i.e. unknown by end user
class Rectangle extends Shape
{
void draw()
{
System.out.println("drawing rectangle");
}
}
class Circle1 extends Shape
{
void draw()
{
System.out.println("drawing circle");
}
}
//In real scenario, method is called by programmer or user
class TestAbstraction1{
public static void main(String args[]){
Shape s=new Circle1();//In real scenario, object is provided through method e.g. getShape() method
s.draw();
}
}

INHERITANCE IN JAVA
Inheritance can be defined as the process where one object acquires the properties of another existing
class. A class that is derived from another class is called subclass and inherits all fields and methods of
its superclass.

Various types of inheritance are as follows.

1) SINGLE INHERITANCE
When a class extends another one class only then it is called as single inheritance. The below flow
diagram shows that class B extends only one class which is A. Here A is a parent class of B and B would
be a child class of A.

Eg :
Class A
{
public void methodA()
{
System.out.println("Base class method");
}
}
Class B extends A
{
public void methodB()
{
System.out.println("Child class method");
}
public static void main(String args[])
{
B obj = new B();
obj.methodA(); //calling super class method
obj.methodB(); //calling local method
}
}

2) MULTIPLE INHERITANCE
“Multiple Inheritance” refers to the concept of one class extending (Or inherits) more than one base
class. Mulitple inheritance is not supported directly in Java. The problem with “multiple inheritance” is
that the derived class will have to manage the dependency on two base classes. In Java multiple
inheritance is made possible through interfaces.

3) MULTILEVEL INHERITANCE
Multilevel inheritance refers to a mechanism where one can inherit from a derived class, thereby making
this derived class the base class for the new class.

Eg:
Class X
{
public void methodX()
{
System.out.println("Class X method");
}
}
Class Y extends X
{
public void methodY()
{
System.out.println("class Y method");
}
}
Class Z extends Y
{
public void methodZ()
{
System.out.println("class Z method");
}
public static void main(String args[])
{
Z obj = new Z();
obj.methodX(); //calling grand parent class method
obj.methodY(); //calling parent class method
obj.methodZ(); //calling local method
}
}

4) HIERARCHICAL INHERITANCE
In hierarchical inheritance one class is inherited by many sub classes. In below example class B,C and
D inherits the same class A. A is parent class (or base class) of B,C & D.

Eg:
Class A
{
public void methodA()
{
System.out.println("method of Class A");
}
}
Class B extends A
{
public void methodB()
{
System.out.println("method of Class B");
}
}
Class C extends A
{
public void methodC()
{
System.out.println("method of Class C");
}
}
Class D extends A
{
public void methodD()
{
System.out.println("method of Class D");
}
}
Class MyClass
{
public void methodB()
{
System.out.println("method of Class B");
}
public static void main(String args[])
{
B obj1 = new B();
C obj2 = new C();
D obj3 = new D();
obj1.methodA();
obj2.methodA();
obj3.methodA();
}
}

5) HYBRID INHERITANCE
Hybrid inheritance is a combination of Single and Multipleinheritance. A hybrid inheritance can be
achieved in the java in a same way as multiple inheritance that is using interfaces. By using interfaces we
can have multiple as well as hybrid inheritance in Java.

Eg:
interface A
{
public void methodA();
}
interface B extends A
{
public void methodB();
}
interface C extends A
{
public void methodC();
}
class D implements B, C
{
public void methodA()
{
System.out.println("MethodA");
}
public void methodB()
{
System.out.println("MethodB");
}
public void methodC()
{
System.out.println("MethodC");
}
public static void main(String args[])
{
D obj1= new D();
obj1.methodA();
obj1.methodB();
obj1.methodC();
}
}

Conclusion

1. Inheritance in Java is supported using extends and implements keywords.


2. When classes are made final, inheritance will not be allowed. final classes cannot be extended in
Java and any attempt to inherit final class will result in compile time error.
3. Constructor in Java are not inherited by Sub Class.
4. Private members of Super class is not visible to Sub class even after using Inheritance in Java.
Private members include any private field or method in Java.
5. Java has a special access modifier known as protected which is meant to support Inheritance in
Java. Any protected member including protected method and field are only accessible in Child
class or Sub class outside the package on which they are declared.

PACKAGES AND INTERFACES


Packages
Packages are containers for classes that are used to keep classes and interfaces together in one space
Package is a mechanism of partitioning the class namespace into manageable chunks.
Benefits of packages are
 Classes in the package of other programs can be easily reused
 Classes are unique within a single package
 Two classes in two different packages can have the same name. They are referred by package
name and class name
 Package provide a means of hiding the classes
 Packages separate “design” from “coding”.

Java packages are divided into two categories


1. Java API packages
2. User defined packages

Java API Packages


There are two ways of accessing built in packages
1. Using fully qualified class name
Eg: java.awt.colour
2. Using import statement
import packagename.classname;
(or)
Import packagename.*

Userdefined packages
Userdefined packages are created using package command

Syntax:
Package packagename;
Public class classname
{
..
}
Example:
Package mypkg;
Public class firstclass
{
System.out.println(“Welcome_packages”);
}

 The package is store in a directory called “mypkg” with filename as “firstclass.java”.


 When compiled the .class file is stored in the same directory “mypkg”.

Step to create package


1. Declare the package at the beginning of a file using package packagename;
2. Define the class that is to be put in the package and declare it as public
3. Create a subdirectory under the directory where main source files are stores.
4. Store the listing as classname.java file in the subdirectory created.
5. Compile the file. This creates .class file in the subdirectory.

 Packages hierarchy is specified using dots.


Eg: package pkg1.pkg2;

Importing Packages
Java includes the import statement to bring certain classes, or entire packages, into visibility.
In a Java source file, import statements occur immediately following the package statement
(if it exists) and before any class definitions. This is the general form of the import statement:

import pkg1[.pkg2].(classname|*);

The packages thus created are used in the required program using import statement
import pkg1.[.pkg2][pkg3].classname;
Eg: import mypkg.firstclass;

Example for userdefined packages

package pkg1;
public class class A
{
public void disA()
{
System.out.println(“class A”);
}
}
import pkg1. class A;
class pkgtest1
{
public static void main(String args[])
{
Class A obj A=new class A();
Obj A.dis A();
}
}

package pkg2;
public class B
{
protected int m=10;
public void dis B()
{
System.out.println(“class B”);
System.out.println(“m=” +m);
}
}

import pkg1.class A;
import pkg2.*;
class pkgtest2
{
public static void main(string args[])
{
Class A obj A =new class A();
Class B obj B=new class B();
Obj A.dis A();
Obj B.dis B();
}
}

Output :
Class A
Class B
m=10

INTERFACE
 Java dose not support multiple inheritance. That is, classes in java cannot have more than one
superclass
 An alternate approach to support the concept of multiple inheritance is the use of interfaces
 Interfaces, like classes, contain methods and variables.
 The difference between interface and class is that interface define only abstract methods and
final fields.
 With interface, Java allows to utilize “one interface, multiple methods” aspect of polymorphism.

Defining an Interface
An interface is defined much like a class. This is the general form of an interface:

access interface name {


return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
type final-varname1 = value;
type final-varname2 = value;
// ...
return-type method-nameN(parameter-list);
type final-varnameN = value;
}

 Variable are declared as static final constants.


Static final type variablename=value;
 Method declaration would be
Return type methodnam1(parameter_list);

Eg:
interface area
{
final static float pi=3.142f;
float compute(float x, float y);
void show();
}

Extending interface
Interface can also be extended similar to classes

Format is
Interface intname2 extends intname1
{
//body of intname2
}

Eg:
interface item C
{
int code=100;
}
interface item extends item C
{
Void display();
}

Several interface can be combined into a single interface


Eg:
Interface item C
{ int code=100; }
interface item M
{ void disp();}
Interface item extends itemC,item
{
}

Implementing Interfaces
Once an interface has been defined, one or more classes can implement that interface. To
implement an interface, include the implements clause in a class definition, and then create
the methods defined by the interface. The general form of a class that includes the implements clause
looks like this:

class classname [extends superclass] [implements interface [,interface...]]


{
// class-body
}

If a class implements more than one interface, the interfaces are separated with a comma. If a class
implements two interfaces that declare the same method, then the same method will be used by clients of
either interface. The methods that implement an interface must be declared public. Also, the type
signature of the implementing method must match exactly the type signature specified in the interface
definition.Here is a small example class that implements the Callback interface shown earlier.

class Client implements Callback {


// Implement Callback's interface
public void callback(int p) {
System.out.println("callback called with " + p);
}
}

ACCESS SPECIFIERS
Java Access Specifiers (also known as Visibility Specifiers ) regulate access to classes, fields and
methods in Java.These Specifiers determine whether a field or method in a class, can be used or invoked
by another method in another class or sub-class. Access Specifiers can be used to restrict access. Access
Specifiers are an integral part of object-oriented programming.

Types Of Access Specifiers :


In java we have four Access Specifiers and they are listed below.
1. public
2. private
3. protected
4. default(no specifier)

public specifiers :
Public Specifiers achieves the highest level of accessibility. Classes, methods, and fields declared as
public can be accessed from any class in the Java program, whether these classes are in the same package
or in another package.

private specifiers :
Private Specifiers achieves the lowest level of accessibility.private methods and fields can only be
accessed within the same class to which the methods and fields belong. private methods and fields are not
visible within subclasses and are not inherited by subclasses. So, the private access specifier is opposite to
the public access specifier. Using Private Specifier we can achieve encapsulation and hide data from the
outside world.

protected specifiers :
Methods and fields declared as protected can only be accessed by the subclasses in other package or any
class within the package of the protected members' class. The protected access specifier cannot be applied
to class and interfaces.

default(no specifier):
When you don't set access specifier for the element, it will follow the default accessibility level. There is
no default specifier keyword. Classes, variables, and methods can be default accessed.Using default
specifier we can access class, method, or field which belongs to same package,but not from outside this
package.
Eg:
package pckage1;
class BaseClass {
public int x = 10;
private int y = 10;
protected int z = 10;
int a = 10; //Implicit Default Access Modifier
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
private int getY() {
return y;
}
private void setY(int y) {
this.y = y;
}
protected int getZ() {
return z;
}
protected void setZ(int z) {
this.z = z;
}
int getA() {
return a;
}
void setA(int a) {
this.a = a;
}
}

public class SubclassInSamePackage extends BaseClass {

public static void main(String args[]) {


BaseClass rr = new BaseClass();
rr.z = 0;
SubclassInSamePackage subClassObj = new SubclassInSamePackage();
//Access Modifiers - Public
System.out.println("Value of x is : " + subClassObj.x);
subClassObj.setX(20);
System.out.println("Value of x is : " + subClassObj.x);
//Access Modifiers - Public
// If we remove the comments it would result in a compilaton
// error as the fields and methods being accessed are private
/* System.out.println("Value of y is : "+subClassObj.y);

subClassObj.setY(20);

System.out.println("Value of y is : "+subClassObj.y);*/
//Access Modifiers - Protected
System.out.println("Value of z is : " + subClassObj.z);
subClassObj.setZ(30);
System.out.println("Value of z is : " + subClassObj.z);
//Access Modifiers - Default
System.out.println("Value of x is : " + subClassObj.a);
subClassObj.setA(20);
System.out.println("Value of x is : " + subClassObj.a);
}
}
Output
Value of x is : 10
Value of x is : 20
Value of z is : 10
Value of z is : 30
Value of x is : 10
Value of x is : 20

You might also like