You are on page 1of 12

FROM JAVA IN A NUTSHELL

**********************************
OPERATIONS
*********************************
--These types are defined in java. Floating-point arithmetic never throws except
ions, even when performing illegal operations, like dividing zero by zero or tak
ing the square root of a negative number.
double inf = 1.0/0.0; // Infinity
double neginf = -1.0/0.0; // Negative Infinity
double negzero = -1.0/inf; // Negative zero
double NaN = 0.0/0.0; // Not-a-number (NaN)
--When operating with integers, trying to compute a value modulo zero causes an
ArithmeticException. When working with floating-point values, anything modulo 0
.0 evaluates to NaN, as does infinity modulo anything.
--The sign of modulo result is the same as the sign of the first operand.
--The + operator (and the related += operator) also concatenates, or joins, st
rings. If either of the operands to + is a string, the operator converts the o
ther operand to a string.
--To test whether a floatingpoint value is NaN, use the Float.isNan()or Double.i
sNan()method.
--if (data != null && i < data.length && data[i] != -1)
... the second and first conditions are not guaranteed to operate if first i
s false. Compare with ||.
The second and third comparisons in this expression would cause errors if the
first or second comparisons evaluated to false. Fortunately, we dont have to wor
ry about this because of the conditional behavior of the && operator.
--The
instanceof operator can be used only with reference types and objects,
not primitive types and values. instanceof requires an object or array value a
s its left operand and the name of a reference type as its right operand. It eva
luates to true if the object or array is an instance of the specified type; it r
eturns false otherwise.
*****************************************
FLOW CONTROL
*****************************************
--for loop syntax: Both the initialize and update expressions of a for loop
can use a comma to separate multiple initializations and update expressions. For
example:
for(int i = 0, j = 10 ; i < 10 ; i++, j--)
sum += i * j;
--for loops are not restricted to loops that count numbers. For example, you mig
ht use a for loop to iterate through the elements of a linked list:
for(Node n = listHead; n != null; n = n.nextNode())
process(n);
--foreach loop is used for handling collections of objects that need to be loope
d over.
for( declaration : expression )
statement
Or better in more descriptive way: read as "for each variable in collection"
for( variable : collection )
statement

--The break statement causes the Java interpreter to immediately exit the innermo
st containing while, do, for, or switch statement (It has to be ome of these typ
es of statements). If followed by the name of a containing labeled statement, br
eak causes the Java interpreter to immediately exit the named block, which can b
e any kind of statement (in this case, not just a loop or switch; that s why we
say block).
--Continue: While a break statement exits a loop, a continue statement quits
the current iteration of a loop and starts the next one. The continue statement,
in both its unlabeled and labeled forms, can be used only within a while, do, o
r for loop. When used without a label, continue causes the innermost loop to sta
rt a new iteration. When used with a label that is the name of a containing loop
, it causes the named loop to start a new iteration.
--NOTE: With the continue statement, update condition gets evaluated in the fo
r loop but not in the equivalent whileloop, before the loop is iterated again.
--return statement: A returnstatement tells the Java interpreter to stop executi
ng the current method. If the method is declared to return a value, the returns
tatement must be followed by an expression. The value of the expression becomes
the return value of the method.
***********************************
METHODS
***********************************
--The values passed to a method need not have exactly the same type as specified
in the signature, but they must be convertible to those types without casting.
--If a method uses the throw statement to throw a checked exception, or if it ca
lls some other method that throws a checked exception and does not catch or hand
le that exception, the method must declare that it can throw that exception.
--If a class is declared final, all the methods of the class are implicitly fina
l. A final method cannot be overidden or hidden by a subclass.
--All private methods are implicitly final ; anyway, they are only accessible
in the class they are defined. They are invisible to subclasses.
--The
native modifier specifies that the method implementation is written in
some native language such as C and is provided externally to the Java program. Li
ke abstract methods, native methods have no body: the curly braces are replaced
with a semicolon. Native methods are used to interface Java code to existing lib
raries written in C or C++.
--The synchronized modifier prevents two threads from executing a method at th
e same time. Thread must obtain a lock on the method s class (if static method)
or on the relevant instance of the class (for non-static methods). Note that met
hods can themselves thread safe in other ways, so don t rely on this.
--Methods may be declared to accept, and may be invoked with, variable number of
arguments. Such methods are commonly
known as varargs methods. E.g.
public static int max(int first, int ... rest) {
Declared by following the type of the last argument to the method with an ell
ipsis (), indicating that this last argument can be repeated zero or more times.
They operate by converting the variable number of arguments into an array. To th
e Java runtime, the max() method is indistinguishable from this one:

public static int max(int first, int[] rest) {


That means you can call them with an array of the given type.
********************
EXCEPTIONS
********************
--Checked exceptions arise in specific, well-defined circumstances, and very oft
en are conditions from which the application may be able to partially or fully r
ecover. We can predict or anticipate them. The Java compiler checks to make sure
you have declared them in method signatures and produces a compilation error if
you have not (that s why they are called checked).
--Unchecked exceptions are set of failures that cannot easily be predicted or an
ticipated, due to such things as runtime conditions or abuse of library code. An
y exception object that is an Error or its subclass, a subclass of Exception ca
lled RuntimeException(or its subclass) is also an unchecked exception. All other
exceptions are checked exceptions.
--If you write a method that throws a checked exception, or if your method calls
a method that can throw a checked exception, you must either include exceptionhandling code (such as try clause) to handle that exception or use throws to dec
lare that your method can also throw that exception.
**********************************
CLASSES
**********************************
--Classes simply define new data types; so a class represents a data type. Concr
ete existance or instance of that data types are called objects.
--Each java file can contain at most one top-level class that is declared publi
c.
--A class can contain any number of nested or inner classes.
--Creating an object is achieved by
i.
using the new operator, foolowed by the objects class (i.e., its
type) and an optional argument list in parentheses.
ii.
using build-in object literals such as
a. String literal
b. type literal by using the class named Class (eg. Class<?
> typeInt = int.class; ). Instances of the Class class represent a Java data t
ype, and contain metadata about the type that is referred to. To include a Clas
s object literally in a Java program, follow the name of any data type with .cl
ass.
c.
null reference. You can assign null to variables of any
reference type. The null value is unique because it is a member of every refere
nce type. It is a reference to nothing, or an absence of a reference.
iii. dynamic loading
iv.
the fact that objects can also be created by deserializing them.
********************************
STRING
*******************************
--string literals cannot be broken across lines, Use the + operator to concaten
ate the literals accross lines.
********************************************
LAMBDA EXPRESSIONS
*******************************************
-- A lambda expression is essentially a function that does not have a name, and
can be treated as a value in the given programming language.
--The syntax for lambda expression is ( paramlist ) -> { statements }. The param

eter list may be empty.


e.g. Runnable r = () -> System.out.println("Hello World");
***************
ARRAYS
***************
--All the elements of an array must be of same type.
--The element type of an array may be any valid Java type, including array types
.
--Array types are reference types, just as classes are, but Array types are not
classes, although array instances are objects. This means that arrays inherit th
e methods of java.lang.Object.
--Arrays implement the Cloneable and Serializable interfaces so that they can b
e cloned and serialized if its element type can be serialized.
--The clone() method makes a shallow copy. If the element type of the array is
a reference type, only the references are copied, not the referenced objects the
mselves. Because the copy is shallow in cloning of objects, any array can be clo
ned, even if the element type is not itself Cloneable.
--all arrays have a public final int field named length that specifies the nu
mber of elements in the array.
--Because arrays extend Object and implement the Cloneableand Serializable
interfaces, any array type can be widened to any of these three types.
eg.
String[] arrayOfStrings; // Created elsewhere
Object o = arrayOfStrings;
--Array literals are created and initialized when the program is run, not when t
he program is compiled. It means that the expressions in an array initializer ma
y be computed at runtime and need not be compile-time constants.
eg. Point[] points = { circle1.getCenterPoint(), circle2.getCenterPoint() };
--Indexing an array with an expression of type long generates a compile-time er
ror, even if the value of that expression at runtime would be within the range o
f an int.
--A common bug involving arrays is use of an index that is too small (a negative
index) or too large (greater than or equal to the array length). Java guarante
es predictable results by checking every array access at runtime. If an array in
dex is too small or too large, Java immediately throws an ArrayIndexOutOfBounds
Exception.
--When cloning an array a cast is required to convert the return value to the ap
propriate array type.
eg. int[] data = { 1, 2, 3 };
int[] copy = (int[]) data.clone();
Because the copy is shallow, any array can be cloned, even if the element ty
pe is not itself Cloneable.
--The System.arraycopy() method is designed to copy elements from one existing
array to another existing array.
--The java.util.Arrays class contains a number of static utility methods for w
orking with arrays.
--When the elements of an array are themselves arrays, we say that the array is
multidimensional.
-- When using the keyword new with multidimensional arrays, you do not have to
specify a size for all dimensions of the array, yuo may state only the leftmost
dimension or dimensions.
--When you create a multidimensional array using the new keyword, it is usually
good practice to only use rectangular arrays: one in which all the array values
for a given dimension have the same size.
********************************************
PRIMITIVE AND REFERENCE TYPES
********************************************
--Reference types are classes, interfaces, arrays, enumerated types and annotati
on types. There are only five ref. types in Java.

--Eight primitive types are defined by the Java language, and the programmer can
not define new primitive types. Reference types are user-defined, so there is an
unlimited number of them.
--Primitive types represent single values. Reference types are aggregate types t
hat hold zero or more primitive values or objects.
--Primitive types require between one and eight bytes of memory. When a primitiv
e value is stored in a variable or passed to a method, the computer makes a copy
of the bytes that hold the value. Two copies are now present.
--Objects, on the other hand, may require substantially more memory. Memory to s
tore an object is dynamically allocated on the heap when the object is created a
nd this memory is automatically garbage collected when the object is no longer nee
ded. When an object is assigned to a variable or passed to a method, the memory
that represents the object is not copied. Instead, only a reference to that memo
ry is stored in the variable or passed to the method. There is still a single co
py of the object.
--The equality operator (==) tests whether two references refer to the same obje
ct; it does not test whether two objects have the same content! But when used wi
th primitive values, it simply tests whether two values are identical (i.e., whe
ther they have exactly the same bits).
--To test whether two objects have equal content, pass one of them to the equals
() method of the other:
eg. object1.equals(object2)
--All objects inherit an equals() method (from Object), but the default implemen
tation simply uses == to test for identity of references, not equality of conte
nt. A class that wants to allow objects to be compared for equality can define i
ts own version of the equals() method. Point class, for instance, does not do t
his, but the String class does. You can call the equals() method on an array,
but it is the same as using the == operator, because arrays always inherit the
default equals() method that compares references rather than array content. You
can compare arrays for equality with the convenience method java.util.Arrays.equ
als() to get equality of content.
--The wrapper classes Boolean, Byte, Short, Character, Integer, Long, Float,
and Double are immutable, final classes which are usually used when you want to
store primitive values in collections such as java.util.List.
--When you assign a value to a variable or pass a value to a method, boxing or u
nboxing conversions are automatically performed. Because Java performs boxing an
d unboxing automatically, this language feature is often known as autoboxing.
eg.

Integer i = 0; // int literal 0 boxed to an Integer object


Number n = 0.0f; // float literal boxed to Float and widened to N

umber
Integer i = 1; // this is a boxing conversion
int j = i; // i is unboxed here
i++; // i is unboxed, incremented, and then boxed up again
Integer k = i+2; // i is unboxed and the sum is boxed up again
i = null;
j = i; // unboxing here throws a NullPointerException
--Autoboxing makes dealing with collections much easier as well:
eg.
List<Integer> numbers = new ArrayList<>(); // Create a List of I
nteger
numbers.add(-1); // Box int to Integer
int i = numbers.get(0); // Unbox Integer to int
*******************************
PACKAGE AND IMPORTS
******************************
--If you are developing a Java application and will not be releasing any of the
classes for reuse by others, you do not have to worry about unforeseen naming co

nflicts. One common approach is to use the application name as the main package
name (it may have subpackages beneath it).
--API developers should use there domain name, with its elements reversed, as th
e prefix for all their package names. This makes their classes have universally
unique fully qualified names and avoid name conflict with classes in the APIs de
veloped by others.
--import declarations must appear at the start of a Java file, immediately after
the package declaration, if there is one, and before any type definitions.
--A form of import is the on-demand type import, where you specify the name of a p
ackage followed by the characters .* to indicate that any type from that packa
ge may be used without its package name. This does not explicitly import all typ
es as may be assumed. Only types that you actually use in your code are imported
, not just everything in the package.
--You can import the static members of types by using the keywords "import stati
c". This means you can import static methods and fields (usually constants) from
classes directly.
--Using static member import declarations for constants is generally a better te
chnique than implementing an interface that defines the constants.
--If you use static import to import static methods from a class in which there
is more than one static method with that name (method overloading), java always
picks one of the methods depending on the parameters you passed and the method s
arguments. (So, you only really import a name not a particular method, the me
thod is decided when you make a call). It is even legal to import static methods
with the same name from two or more different types as long as the methods all
have different signatures.
Here is one naturalexample:
import static java.util.Arrays.sort;
import static java.util.Collections.sort;
--Java packages do not nest, so javanut.ch03.different is just a different package
than javanut.ch03; it is not contained inside it or related to it in any way.
********************************************************************************
*******************
OO PROGRAMMING CONCEPTS: CLASS, INTERFACE, ENUM and ANNOTATED TYPES
********************************************************************************
*******************
--An object is a collection of data and the methods that operate on that data; t
he data fields and methods of an object are called its members.
--From Java 8 onward, interfaces may use the keyword default to modify a metho
d and to indicate that the method specified in the interface is optional.
--Classes and interfaces are the most important of the five fundamental referenc
e types defined by Java. Arrays, enumerated types (or enums), and annotation types
(usually just called annotations) are the other three.
--Enums are a specialized kind of class and annotations are a specialized kind o
f interface.
--If a method is optional, the interface file must include a default implementat
ion (hence the choice of keyword) which will be used by all implementing classes
that do not provide an implementation of the optional method.
--Enums are a specialized kind of class and annotations are a specialized kind o
f interface.
--Class defination is exemplefied below, with keywords in the given order: acces
s modifier, other modifiers and annotation, keyword class, name, extends other c
lass, implements some method(s) separeted by commas.
eg. public class Integer extends Number implements Serializable, Comparable
{
// class members go here
}
--A generic class may also have type parameters and wildcards as part of its def
inition.
--An abstract class is one whose implementation is incomplete and cannot be i

nstantiated. Any class with one or more abstract methods must be declared abstr
act.
--The final modifier specifies that the class may not be extended. A class can
not be declared to be both abstract and final.
*****************************
1. Fields and Methosd
*****************************
--The use of public static fields that are not final is almost never a good pra
cticeas multiple threads could update the field and cause behavior that is extrem
ely hard to debug.
--The key point to understand about a static field is that there is only a singl
e copy of it.
--A class method can use any class fields and class methods of its own class (or
of any other class), but it cannot use any instance fields or instance methods
because class methods are not associated with an instance of the class. Recall t
hat we always have a this reference to the current object. But class methods a
re not associated with a specific instance, so have no this reference, and no
access to instance fields.
--Any field or method declared without the static modifier is an instance field
or method.
--Every instance (object) of the class has its own copy of instance field. They
are the fields every object of the class must have; eg. every Circle object must
have a radius, so radius should be defined as an instance field not class field
.
--Instance fields define object s state, while instance methods define the objec
t s behavior.
--On the other hand, class fields and methods are just utility fields and utilit
y methods.
--Instance fields are the key to object-oriented programming. Instance fields ho
ld the state of an object; the values of those fields make one object distinct f
rom another.
--In code outside the class, to access an instance method or instance field, the
name of that instance method or field must be prefixed with a reference to the
object of the class that contains it. For example, if the variable c holds a ref
erence to a Circle object, we use the expression c.r to refer to the radius of
that Circle object:
eg.
Circle c = new Circle();
// Create a Circle object; store a ref i
n c
c.r = 2.0;
// Assign a value to its instance field
r
Circle d = new Circle();
// Create a different Circle object
d.r = c.r * 2;
// Make this one twice as big
--To use an instance method from outside the class in which it is defined, we mu
st prefix it with a reference to the instance that is to be operated on. For exa
mple:
Circle c = new Circle();

// Create a Circle object; store in vari

c.r = 2.0;
double a = c.area();

// Set an instance field of the object


// Invoke an instance method of the obje

able c
ct
--Instance methods are not restricted: they can use any member (field or method)
of their class, whether it is declared static or not.
--The this keyword is used as a reference to the current class object. You can
use the this keyword explicitly when you want to make it clear that a method
is accessing its own class fields and/or methods. For example, we can rewrite

public double area() { return Circle.PI * this.r * this.r; }


This area() method use this explicitly to refer to instance fields of the s
ame class, but this is not usually needed as it is implicitly known by the compi
ler. This code also uses the class name explicitly to refer to class field PI.
In more complicated cases, however, you may sometimes find that it increases the
clarity of your code to use an explicit this where it is not strictly require
d.
In some cases, the this keyword is required, however. For example, when a m
ethod parameter or local variable in a method has the same name as one of the fi
elds of the class, you must use
this to refer to the field, because the field
name used alone refers to the method parameter or local variable.
eg.
public void setRadius(double r) {
this.r = r;
// Assign the argument (r) to th
e field (this.r)
// Note that we cannot just say r = r
}
Finally, note that while instance methods can use the this keyword, class
methods cannot. This is because class methods are not associated with individual
objects.
--When an instance method overides the one in its superclass the return type of
the overriding method may be a subclass of the return type of the original metho
d (instead of being exactly the same type). This is known as a covariant return.
--Just like fields, class methods can be hidden by a subclass but cannot be over
ridden.
--Method overloading refers to the practice of defining multiple methods (in the
same class) that have the same name but different parameter lists. (This very d
ifferent from method overriding).
-*************************
2. Constructors
************************
--constructorsthese are class members whose job is to initialize the fields of a
class as new instances of the class are created. It has the same name as the cla
ss, and has a body, like a method. It has no any return type.
--We can define multiple constructors for a class, as long as each constructor h
as a different parameter list.
--If one constructor uses this() to call another constructor because they share
some initialisation code, the this () call can appear only as the first statem
ent in the constructorbut the call may be followed by any additional initializati
on a particular constructor needs to perform. The reason for this restriction in
volves the automatic invocation of superclass constructors.
--All instance fields are initialized within the very constructor that create th
e instance (even if it refer to another constructor) at the time of creation of
the the instance. But class fields are already initialized even before any insta
nce occur, even before any constructor of the class is called.
--Initialisation of fields, whether class or instance fields, are done in the or
der in which they appear in the source code. This means that the initialization
expression for a class field or instance field can use the class fields or insta
nce fields declared before it.
--If you are creating a public class that should not be publicly instantiated,
you should declare at least one non-public constructor to prevent the insertion
of a default public constructor by the JVM. Classes that should never be insta
ntiated (such as java.lang.Math or java.lang.System) should define a private con
structor. Such a constructor can never be invoked from outside of the class, but
it prevents the automatic insertion of the default constructor.
**************************************

3. Static Initialisation Block


*************************************
--Java allow us to write arbitrary code for the initialization of class fields w
ith a construct known as a static initializer. A static initializer is simply th
e keyword static followed by a block of code in curly braces. A static initializ
er can appear in a class definition anywhere a field or method definition can ap
pear.
eg.
// We can draw the outline of a circle using trigonometric funct
ions
// Trigonometry is slow, though, so we precompute a bunch of values
public class TrigCircle {
// Here are our static lookup tables and their own initializers
private static final int NUMPTS = 500;
private static double sines[] = new double[NUMPTS];
private static double cosines[] = new double[NUMPTS];
// Here s a static initializer that fills in the arrays
static {
double x = 0.0;
double delta_x = (Circle.PI/2)/(NUMPTS-1);
for(int i = 0, x = 0.0; i < NUMPTS; i++, x += delta_x) {
sines[i] = Math.sin(x);
cosines[i] = Math.cos(x);
}
}
// The rest of the class is omitted...
}
A class can have any number of static initializers.
--A class can also instance initializers. An instance initializer is like a stat
ic initializer and looks just like a static initializer, except that it doesnt us
e the static keyword. Every instance of the class will have a copy of them in i
ts construcor.
***************************************
4. Inheritance
***************************************
--When a subclass inherits a parent class, it can call the constructor of the p
arent class the deyword super() . super must be the first word in the constru
ctor of the subclass. The constructor of the subclass will explicitly initialize
its fields that are newly defined by it, but it will rely on the superclass co
nstructor to initialize the inherited fields of the class. The arguments passed
to super() must match the parameters of the superclass constructor.
--Narrowing conversions require a cast (and a runtime check by the VM), but wide
ning conversion does not:
eg. if PlaneCircle is a sub-class of Circle (it extends Circle), then;
PlaneCircle pc = new PlaneCircle(1.0, 0.0, 0.0);
Circle c = pc; // Assigned to a Circle variable without casting
(b/c it is a widening conversion).
but,
PlaneCircle pc2 = (PlaneCircle) c; //casting required for narrow
ing conversion.
boolean origininside = ((PlaneCircle) c).isInside(0.0, 0.0); // i
sInside() is a method in PlaneCircle, a sub-class; therefore, casting required o
n c.
--A subclass relies on the superclass constructor to initialize the inherited fi
elds of the class.
--Constructor calls are chained; any time an object is created, a sequence of co
nstructors is invoked, from subclass to superclass on up to Object at the root o
f the class hierarchy. Therefore, whenever a constructor is invoked, it can coun
t on the fields of its superclass to be initialized by the time the constructor
starts to run.

--If a constructor does not invoke a superclass constructor, Java does so implic
itly. Also, Java implicitly adds a constructor to a class declared without any c
onstructor. This default constructor does nothing but invoke the super class con
structor.
--In general, if a class does not define a no-argument constructor, all its subc
lasses must define constructors that explicitly invoke the superclass constructo
r with the necessary arguments.
--If both subclass and superclass declare the same instance field, say r, then
r // Refers to the subclass field
this.r // Refers to the subclass field
super.r // Refers to the superclass field
or we can just write
((SuperclassName) this).r // Refers to field r of the Superclass. This
way of casting this to a superclass works at any depth of inheritance.
--In code that you write, you should avoid declaring fields with names that hide
superclass fields. It is almost always a sign of bad code.
--As for class field (static), we can always refer to a class field by prependin
g the name of the desired class; such as Circle.PI to refer to the static PI fie
ld in class Circle.
--When we cast an instance (object) of a subclass to a superclass and assign it
to an instance of the superclass as shown below, where b is an instance of B
, a subclass of A :
//Here we see a salient difference between instace field and instance me
thods.
A a = (A) b; // Casts b to an instance of class A
System.out.println(a.i); // Now refers to A.i (Both A and B defined a da
ta i). B.i nomore hides A.i
System.out.println(a.f()); // Still refers to B.f() (Both defined f(), a
n instance method in both). B.f() overrides A.f()
System.out.println(a.g()); // Refers to A.g() (Both defined g(), a class
method in both). A.g(), a class method, is never overidden.
System.out.println(A.g()); // A better way to invoke A.g()
Here, we understand that although Java treats the fields and methods of a clas
s analogously in many ways, method overriding is not like field hiding at all. Y
ou can refer to hidden fields simply by casting an object to an instance of the
appropriate superclass, but you cannot invoke overridden instance methods with t
his technique.
--Virtual method lookup at runtime: in the above case, the interpreter looks up
the appropriate f() method to call for an object by checking the actual runtime
type of the object referred to by the variable a , starting the lookup from thi
s class; if the actual runtime type is A it calls the f() in A , if the actua
l runtime type is B it calls the f() in B . In the above case b is an actua
l instance of B , so it uses the f() in B .
--To invoke the overriden method in a superclass, we use the super keyword, an
d we can do the same for a hidden field: if a subclass defines an instance field
i and an instance method f() to hide and override the ones in its superclass
respectively, we can simply access the ones in the superclass from within the su
bclass as follows:
super.i //or A.i if the superclass is A .
and
super.f() // or A.f(). Whenever super is used virtual method lookup
starts at the superclass and move up the hierarchy, it will not even bother to c
heck the method in the subclass.
respectively. Note that, in the previous code, the expression super.f() is not
the same as ((A)this).f()
-- super , as used above, can be used only to invoke an overridden method FROM
WITHIN the class that overrides it, and not by an external code using the subcla
ss.
--For narrowing conversion, only cast an object to the type of a subclass if you
are sure, based on the logic of your program, that the object is actually an in
stance of the subclass. If it is not, the interpreter throws a ClassCastExceptio

n. For example, if we assign a String object to a variable of type Object, we ca


n later cast the value of that variable back to type String.
Object o = "string";

// Widening conversion from String


// to Object Later in the pro

gram...
String s = (String) o;

// Narrowing conversion from Object


// to String
-- An object can be converted to the type of its superclass or of any ancestor c
lass. This is a widening conversion, so no cast is required. (No conversion is a
ctually performed; the object is simply treated as if it were an instance of the
superclass. This is referred to as the Liskov substitution principle).
--An object cannot be converted to an unrelated type.
--In addition, an array can be converted to another type of array if the base typ
es of the two arrays are reference types (not primitive types) that can themselve
s be converted.

*******************************************
5. Data Hiding and Encapsulation
*******************************************
--The most important reason for encapsulation is to hide the internal implementa
tion details of your class.
--Call a method from outside to change any field in the inside, that method can
be sure to do everything necessary to keep the state of your class consistent.
--Similarly, if a class defines certain methods or fields for internal use only,
hiding these methods and fields prevents users of the class from calling them.
--If you don t want a static (class member which only one copy is created when t
he class is loaded) member to be accessible to anyone other than this class, you
can declare it private static .
--Default access is more restrictive than protectedas default access does not all
ow access by subclasses outside the package.
--If B is a subclass of A, and A has a protected field say name , then B inheri
ts that field and can use it in its code by calling, for example, super.name e
ven if B is in another different package. However, instances (objects) of B cann
ot read the protected fields from the instances (objects) of A except if both A
and B reside within the same package.
--Use public only for methods and constants that form part of the public API of
the class. The only acceptable usage of public fields is for constants or immuta
ble objects, and they must be also declared final.
--Use protected for fields and methods that arent required by most programmers us
ing the class but that may be of interest to anyone creating a subclass as part
of a different package.
--Use the default package visibility for fields and methods that are internal im
plementation details but are used by cooperating classes in the same package.
--If you are not sure whether to use protected, package, or private accessibilit
y, start with private. If this is overly restrictive, you can always relax the a
ccess restrictions slightly (or provide accessor methods, in the case of fields)
.
*******************************************
JAVA TYPE SYSTEM
*******************************************
************************
1. Interface
************************

-- Like a class, an interface defines a new reference type.


-- All members of an interface are implicitly abstract and public.
-- The only fields allowed in an interface definition are constants that are dec
lared both static and final.
-- Interfaces may contain nested types.
-- From Java 8, an interface may contain static methods.
-- Interfaces may extend one or more comma separated other interfaces using the
extends keyword. A class that implements such an interface must implement the
abstract methods defined directly by the interface, as well as all the abstract
methods inherited from all the superinterfaces.
-- When a class implements an interface it can be treated as an instance of that
interface. Therefore, the use of instanceof to determine the runtime type of an
object is quite often an indication of a problem with the design, an object may
have more than one type.
-- Interfaces are data types in Java, just like classes. When a class implements
an interface, instances of that class can be assigned to variables of the inter
face type.
-- Marker Interfaces are empty interfaces use to provide additional information
about an object. The object is an instance of that interface when its class impl
ements it. E.g java.io.Serealizable interface: it is implemented to tell ObjectO
utputStream that instances of the inheritor may safely be serialized. java.util.
RandomAccess is another example to advertise that an inheritor provides fast ran
dom access to its elements (e.g. java.util.List).
*************************
2. Generics
*************************
-- Generics are used to enable containers know exactly what type of objecs they
contain; so that illegal types are detected at compile time. When generics are u
sed no cast is required.
-- Type parameters used in generics (parameterised types) always stand in for re
ference types. It is not possible to use a primitive type as a value for a type
parameter.
-- A type parameter can be used in the signatures and bodies of methods (Includi
ng return types and arguments) as though it is a real type.
-- Because of type erasure after compilation, two different methods that only di
ffer by the nature of parameterised types from the same class cannot be consider
ed as method overload and results in compile error. This is because when the par
ameters are removed at compilation the two methods become the same.
e.g. int totalOrders(Map<String, List<String>> orders);
int totalOrders(Map<String, Integer> orders);
Both become
int totalOrders (Map);
after compilation when the parameters are removed
--

You might also like