Entities
Index
- Interface
- Introduction
- why use interface
- Relation btw class and interface
- Interface vs Abstract
- Enum
- Definition
- Syntax
Interface
- An interface in java is a blueprint of a class. It has public static final data members 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(true till JDK 1.7) . It is used to achieve full abstraction and multiple inheritance in Java.
- Java Interface also represents IS-A relationship.
- It cannot be instantiated just like abstract class.
- The java compiler adds public and abstract keywords before the interface method and public, static and final keywords before data members.
Why use Java interface?
There are mainly three reasons to use interface.
- It is used to achieve full abstraction.
- By interface, we can support the functionality of multiple inheritance.
- It can be used to achieve loose coupling.
(Interfaces allow complete separation between WHAT(specification or a contract) is to be done Vs HOW (implementation details) it’s to be done
eg : In JDBC (java db connectivity)
java.sql.Connection i/f —-Sun
Imple. classes — DB vendors —
Oracle –Oracle DB engine –Imple cls for Comnection i/f
Red Hat — Mysql — Imple cls for Comnection i/f
Relationship between classes and interfaces
- A class extends another class, an interface extends another interface but a class implements an interface.
- Multiple inheritance in Java by interface
- If a class implements multiple interfaces, or an interface extends multiple interfaces i.e. known as multiple inheritance.
Multiple inheritance in java
interface Printable{
void print();
}
interface Showable{
void show();
}
class A implements Printable,Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}
public static void main(String args[]){
A obj = new A();
obj.print();
obj.show();
}
}
Q-Multiple inheritance is not supported through class in java but it is possible by interface, why?
Multiple inheritance is not supported in case of class, sincee it can create an ambiguity. But it is supported in case of interface because there is no ambiguity as implementation is provided by the implementation class.
Example
interface Printable{
void print();
}
interface Showable{
void print();
}
class TestTnterface1 implements Printable,Showable{
public void print(){System.out.println("Hello");}
public static void main(String args[]){
TestTnterface1 obj = new TestTnterface1();
obj.print();
}
}
Interface inheritance
A class implements interface but one interface extends another interface .
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();
}
}
Q) What is marker or tagged interface?
An interface that have no member is known as marker or tagged interface. For example:
Serializable {java.io pkg abbr:since used for i/o conversion},
Cloneable,(java.lang.Colneable(i/f)–
usage:implementing class override public Object clone(){return super.clone();}) Remote etc. They are used to provide some essential information to the JVM(Run time marker) so that JVM may perform some useful operation.
//How Serializable interface is written?
public interface Serializable{
}
Note: An interface can have another interface i.e. known as nested interface.
eg :
interface printable{
void print();
interface MessagePrintable{
void msg();
}
}
Abstract vs Interface

Inner classes
- Instance inner class
- Method local inner class
- static nested class (can’t call innner )
Rules for inner class
About non-static/Instance inner classes
- The inner class(non-static nested) has access to all of the outer class’s members, including those marked private , directly(without inst.)
- To instantiate an inner class, you must have a reference to an instance of the outer class.
syntax :
Instantiating a non-static nested class requires using both the outer inst and nested class names as follows:
BigOuter.Nested n = new BigOuter().new Nested();
- Such Inner classes can’t have static members.(Java SE 8 –allows static final members)
About method-local inner classes
- A method-local inner class is defined within a method of the enclosing class.
- For the inner class to be used, you must instantiate it, and that instantiation must happen within the same method, but after the class definition code.
- A method-local inner class cannot use variables declared within the method
- (including parameters) unless those variables are marked final or effectively final.
About static nested classes
- A static nested class is not an inner class, it’s a top-level nested class.
- You don’t need an instance of the outer class to instantiate a static nested class.
- It cannot access non-static members of the outer class directly BUT can access static members of the outer class.
- It can contain both static & non-static members.
- JVM will not load any class’s static init block — until u actually refer to something from that class.
- (Lazy loading) This is true for static nested classes too.



Enum
Enumerations (in general) are generally a set of related constants. Supported in Java since JDK 1.5 release.
Enumeration in java is supported by keyword enum. enums are a special type of class that always extends java.lang.Enum.
A simple usage will look like this:
public enum DIRECTION {
EAST,
WEST,
NORTH,
SOUTH //optionally can end with ";"
}
Here EAST, WEST, NORTH and SOUTH are implicitly of type
public final static Direction EAST;
Super class of all enums
public abstract class Enum<E extends Enum<E>>
extends Object
implements Comparable<E>, Serializable
ie. they are comparable and serializable implicitly. All enum types in java are singleton by default.
So, you can compare enum types using ==operator also.
Since enums extends java.lang.Enum, so they can not extend any other class because java does not support multiple inheritance . But, enums can implement any number of interfaces.
enum can be declared within a class or separately.
eg of enum within a class
When declared inside a class, enums are always static by default
eg public class TestOuter
{
enum Direction
{
EAST,
WEST,
NORTH,
SOUTH
}
}
To access a direction — use TestOuter.Direction.NORTH.
Constructors of enum
By default, enums do not require you to give constructor definitions & javac implicitely calls super class constructor
Enum(String name,int ordinal)
Methods of Enum
- Enum[] values() –rets array of enum type of refs.–pointing to singleton objs
- Enum valueOf(String name) — string to enum type converter
- values & valueOf methods generated by compiler –so not part of javadocs.
- If u pass a different name (eg — ABC) to valueOf —throws IllegalArgumentException
- String name() –rets name of constant in string form
- int ordinal() –rets index of the const as it appears in enum.–starts with 0
You can supply your own constructor/s to initialize the state(data member of enum types.
enum Direction {
// Enum types
EAST(0), WEST(180), NORTH(90), SOUTH(270);
// Constructor
private Direction(final int angle) {
this.angle = angle;
}
// Internal state
private int angle;
public int getAngle() {
return angle;
}
}
Wrapper Class
- What’s need of wrapper classes?
- to be able to add prim types to growable collection(growable data structure eg — LinkedList)
- wrapper classes contain useful api(eg — parseInt,parseFloat
- What are wrappers? — Class equivalent for primitive types
- Inheritance hierarchy
- java.lang.Object — Character (char)
- java.lang.Object — Boolean
- Object — Number — Byte,Short,Integer,Long,Float,Double
- Inheritance hierarchy
- Constrs & methods — for boxing & unboxing
- boxing= conversion from prim type to the wrapper type(class type)
- un-boxing = conversion from wrapper type to the prim type
eg
Integer(int data) --- boxing
Integer i1=new Integer(100);
//un-boxing
int data=i1.intValue();
Integer i1=100;//no err from JDK 1.5
sop(i1);
int data=1234;
i1++;//Integer--->int(auto unboxing), inc ,auto box
Object o=123.45;//auto-boxing(double--->Double)--up casted to Object
Number n1=true;//auto-box----X(up casted) to Number
Object o2=false;//auto box -- up casting
Double d1=1234;//auto boxing (int --->Integer) ---X--Double
- JDK 1.5 onwards — boxing &unboxing performed automatically by java compiler,when required. — auto-boxing , auto-unboxing,
String class
Important String class constructors
- String(byte[] bytes) — byte[] —-> String converter
- String(char[] chars) — char[] —> String converter
- String (byte[] bytes,int offset,int len) —byte[] —-> String converter from the specified offset , specified len no of bytes will be converted.
- eg . String s=new String(bytes,3,4); — String will contain bytes[3]—-bytes[6]
- String(char[] ch,int offset,int len)
- String(String s)
String class methods
- charAt,
- compareTo,
- contains,
- copyValueOf,
- format,
- valueOf,
- getBytes,
- toCharArray,
- toLowerCase,
- indexOf,
- lastIndexOf,
- split,
- replace,
- startsWith,
- endsWith,
- length,
- intern
Formatting details
- %c — character
- %b — boolean
- %h — hex value of hashcode of obj ref.
- %s — string
- %d — int
- %f,%g — float/double
- %x — hex value
- %n — line separator
- %tD — Date
- %tT — Time
- %tc — Time stamp(date & Time)
- %td-%1$tb-%1$tY — can be applied to GC or Date.


Date/Time Handling in Java
API
- java.util.Date— represents system date.
- Constructor
- Date() — creates Date class instance representing system date.
- Date(long msec) — creates Date class instance representing date for msec elapsed after epoch(=1st Jan 1970)
- & methods(toString,before,after,equals,compareTo)
- Constructor
- java.util.GregorianCalendar
- month range — 0-11
- GregorianCalendar(int yr,int mon,int date);
- GregorianCalendar(int yr,int mon,int date,int hr,int min,int sec);
- month range — 0-11
- java.sql.Date,Calendar
- Date/Time formatting via printf
- %tc — for complete timestamp(date & time)
- %tD — for date
- %tT — time
How to parse String —> java.util.Date
How to format Date —>String
Steps
- Create instance of parser — java.text.SimpleDateFormat(String pattern)
- yyyy- year
- MM — month in digit (1-12)
- MMM — month name in abbrevation(eg : jan,dec…)
- MMMM –complete month name
- d — day
- hh — hours
- mm — minutes
- ss –seconds
- eg : SDF sdf=new SDF(“dd-MM-yyyy”);
- Inherited method from DateFormat
- public Date parse(String s) throws ParseException
- eg : Date d=sdf.parse(sc.next());
- public Date parse(String s) throws ParseException
- To format Date —> String (as per pattern)
- public String format(Date d)
- eg : sop(d1);
- sop(sdf.format(d1))
- public String format(Date d)
var-args
- variable args syntax.— Must be last arg in the method args.
- Can use primitive type or ref types.
Legal usage-
void doStuff(int... x) {
} // expects from 0 to many ints
Usage : ref.doStuff();
int[] ints={1,2,3,4};
ref.doStuff(ints);
ref.doStuff(20,34,56);
System.out.printf("%n");
// as parameters
void doStuff2(char c, int... x) { } // expects first a char,
// then 0 to many ints
void doStuff3(Animal... animal) { } // 0 to many Animals
invocations ---
ref.doStuff3();
ref.doStuff3( animals);
ref.doStuff3( a1,a2,a3);
Illegal usage
void doStuff4(int x...) { } // bad syntax
void doStuff5(int... x, char... y) { } // too many var-args
void doStuff6(String... s, byte b) { } // var-arg must be last
Varargs overloading
static void vaTest(boolean … v) {
System.out.print("vaTest(boolean …) " + "Number of args: " + v.length + " Contents: ");
for(boolean x : v)
System.out.print(x + " ");
System.out.println();
}
public static void main(String args[])
{
vaTest(1, 2, 3); // OK
vaTest(true, false, false); // OK
vaTest(); // Error: Ambiguous!
}
}
Generic syntax
Introduction
What is it ?
Parameterized types.
- Available from Java SE 5 onwards.
- Represents Parameterized Types.
- Can Create Generic classes, interfaces, methods and constructors.
- Operates on Parameterized data Types
- In Pre-generics world , similar achieved via Object class reference.
Why Generics ? – Advantages
- Adds Type Safety to the code @ compile time
- Can add type safe code where type-mismatch errors are caught at compile time.
- No need of explicit type casting, as all casts are automatic and implicit.
A generic class means that the class declaration includes a type parameter.
eg — class MyGeneric
T —type — ref type
Can Create Generic classes(eg : ArrayList), interfaces(eg : Comparable) , methods(Arrays.sort) and constructors(ArrayList())
E — element
T –Type
K — Key
V – Value
In Pre-generics world , similar achieved via Object class reference.
One thought on “Java Tutorial”