Data types:
Java has two kind of var. types, i.e. primitive and reference type.
Reference variable is used to store a reference, which points to an instance.
Primitive type: byte(8), char(16), short(16bit), int(32), long(64), and floating float(32), double(64), etc
Java use four type integers byte, short, int, and long; and two type of floating-point numbers: float(single precision) and double(double precision). Normally you should use the double type, because it is more accurate than the float type.
suffix: float(F) double(D); and long(L)
octal(0) and hex(0xFFFF) literals:
Type casting is required when assigning a value to a variable of a smaller type range, for instance,
double d = 4.5;
int i = (int i)d
Primitive Wrapper Classes
Each primitive has its reference type, i.e. a wrapper class extended from Number.
Integer a = 1;
Float b = 1.0f;
Can you compare them in a conditional statement?
No. for they have different class type.
Can you use method compareTo() to compare each other?
No. for in the compareTo() method requires the same type of object.
The same principle as applying if(a==b){}; resulting a compilation error, "incompatible types."
However, for the primitive types
int a = 1;
float b = 1.0f;
You may use conditional statement to compare different data types .
Java narrowing primitive convention: applied on the char, byte and short, required to be cast in method invocation.
What happens with the following code?
Short s = new Short(9);
You get a compiling error here. "no suitable constructor", because 9 is considered as a int type.
So, casting
Short s = new Short((short)9);
reference(class): String, Enum, and arrays
Reference variable is used to store a reference, which points to an instance.
Primitive type: byte(8), char(16), short(16bit), int(32), long(64), and floating float(32), double(64), etc
Java use four type integers byte, short, int, and long; and two type of floating-point numbers: float(single precision) and double(double precision). Normally you should use the double type, because it is more accurate than the float type.
suffix: float(F) double(D); and long(L)
octal(0) and hex(0xFFFF) literals:
Type casting is required when assigning a value to a variable of a smaller type range, for instance,
double d = 4.5;
int i = (int i)d
Primitive Wrapper Classes
Each primitive has its reference type, i.e. a wrapper class extended from Number.
Integer a = 1;
Float b = 1.0f;
Can you compare them in a conditional statement?
No. for they have different class type.
Can you use method compareTo() to compare each other?
No. for in the compareTo() method requires the same type of object.
The same principle as applying if(a==b){}; resulting a compilation error, "incompatible types."
However, for the primitive types
int a = 1;
float b = 1.0f;
You may use conditional statement to compare different data types .
Java narrowing primitive convention: applied on the char, byte and short, required to be cast in method invocation.
What happens with the following code?
Short s = new Short(9);
You get a compiling error here. "no suitable constructor", because 9 is considered as a int type.
So, casting
Short s = new Short((short)9);
reference(class): String, Enum, and arrays
Variable Declaring:
In java chained declaring is not allowed. int a = b = c=100 causes a compiling error, for the variable b and c is considered not declared yet. How about this? int a, b, c=100;
Identifier Naming
starting "_" or "$" or any letter; it cannot start with a digit. it cannot be a reserved word; an identifier can be of any length.
$$ is a valid identifier.
int $$ = 0;
In java chained declaring is not allowed. int a = b = c=100 causes a compiling error, for the variable b and c is considered not declared yet. How about this? int a, b, c=100;
Identifier Naming
starting "_" or "$" or any letter; it cannot start with a digit. it cannot be a reserved word; an identifier can be of any length.
$$ is a valid identifier.
int $$ = 0;
Flow Control
Basically,
if ... else
if ... else
if() ... else if() ... else if() ... else
Switch
A switch works with the byte, short, char, and int primitive data types; enum. types; and now String class type. and a few primitive wrapper classes Character, Byte, Short, and Integer.
Note: switch cannot work with long, float and double. Ensure that expression in any switch statement is not null to prevent a NullPointerException from being thrown.
Note: switch cannot work with long, float and double. Ensure that expression in any switch statement is not null to prevent a NullPointerException from being thrown.
Loop: for, while, do-while;
while(Boolean condition){ }do{...}while(Boolean condition)
for(int i;i...}
specific case://infinite loop
for(;;){
}
for(Element e: vector){
...}
break or continue in a loop (labeled or unlabeled )
break without label: quit from entire loop block.
break with label: break from the labeled statement block, which contains a loop or loops.
continue without label: quite from the current iteration, and continue to the next loop.
return
the last of branching statement is the return. 1) return values defined in the method signature; 2) return without any value, meaning that quit from current method, backing to the method invoking point.
Class and Method
Member variables
variables maybe defined by the primitive types, for instance: int, float, double, char, byte , short etc
or by the reference types: String, array(float x[]), or created from classes
variable modifiers: public or private, static final etc.
public: accessible by all classes.
private: only within the class
member variables in the class: fields
variables declared in the block of code or methods; local variables
variables declared in the method argument: parameters(local variables)
member variable modifiers(4 types): public, protected, private and without modifier;
method naming conventionverb(lower case) + (adj. / noun)
Constructor
You many provide no constructor; but compiler may provide a default one (non argument), in which a non-argument constructor will be called from the super class. So you might need to take care of here. If the super class doesn't offer an explicit non-argument constructor, then achieving a compiling error.
Note: If a constructor does not explicitly invoke a super-class constructor, the Java compiler automatically inserts a call to the no-argument constructor, super(), of the super-class. If the super class does not have a no-argument constructor, you will get a compile-time error.
Please note: ref. to super class constructor, super() must be put in the first line of the sub-class constructor.
Object
does have such a constructor, so if Object
is the only super-class, there is no problem.Please note: ref. to super class constructor, super() must be put in the first line of the sub-class constructor.
class modifier: public(accessible by all classes in all packages); or without any modifier(implicitly, accessible by the classes in its package.)
GC Principle.
it could be forced to be released, by setting to be null. it doesn't mean you can force GC to do clearing, but just informing it; he can remove it.
List list = new ArrayList();
VM create an instance ArrayList in the heap memory and gives back the reference value in the list variable;
When the instance has no need any more, then we may set list = null, and inform the GC to recycle this part of resource.
List list = new ArrayList();
VM create an instance ArrayList in the heap memory and gives back the reference value in the list variable;
When the instance has no need any more, then we may set list = null, and inform the GC to recycle this part of resource.
Using this keyword.
1) this is used to ref. to current class instance itself. the purpose is to avoid the shadow of the variable by the method input parameters. public void setAge(int age){this.myAge = age;};
2) this used in the constructor, to refer to other constructors.
this(x,y); invoking used to invoking other class constructor. If present, the invocation of another constructor must be the first line in the constructor. public Human(int age){ this(age,0.0) };
Access control to Class members(fields)
Public: can be accessed from current class, current package, and classed located at external packages; so it could be accessed in anywhere of the application.
Protected: can be accessed from current class, current package, but only the sub-classes located at the other packages
no modifier(default): it does't mean it is the same to private declaring; not at all. on this case, field could be accessed by the classes in the current package; and it is hidden from the sub-classes.
Private: can be only accessed from current class, not even to the sub-classes. fields are truly hidden/encapsulated.
Please note here, class method (static method) cannot access instance method and instance var.
However, instance method can directly access both. The purpose of class fields and methods are for sharing common attributes and behaviors. How about another way round?thus why a class method really interested at a specific instance attribute or method? so this was prohibited .
Class method and class var. keyword (static); there is no need to instantiate instances to access such a var or a method.
Using "import static package" can even over-skip the class qualifications.
Using "import static package" can even over-skip the class qualifications.
Class constants naming: static final, followed by naming; it must be capitals. If more than one word, please using '_' to make them concatenated.
Initialize Class fields
The most simple way to init. them at the start of class. that is what we often do. in the principle, you can init. them in any part the class. certainly we don't do like that.
1) using static block code: static { init. code here } to init. class fields
A static block will be first invoked as the class is loaded by JVM, no matter where it has been put in the class. so no matter what, it will be implemented before the constructor. it could has several static block, and they will be implemented automatically according to their occurrence sequence.
A static block will be first invoked as the class is loaded by JVM, no matter where it has been put in the class. so no matter what, it will be implemented before the constructor. it could has several static block, and they will be implemented automatically according to their occurrence sequence.
2) private static final method: well you have to use a static method to access static fields.
Initialize Instance fields
Certainly we sometime to init. instance fields in the constructor, i.e. declaring instance var at the start of the class, and init. them in the constructors.
sharing common init. code in several constructor? 1) using init. block; Java compiler will copy the block of init. code into each of the constructor. 2) using private final method to re-use the init. code. I think this is a better strategy.
private final void init(){ }
Inner Class
I feel it is really not that often to use inner class. is there a private class? normally, we define classes that we want to use these templates to cast new instances; So in the real life, what is a private class? actually, it is a Inner class.
Class A{ Class B{} }
Interface
Interface is an protocol defined how a group of classes communicate with external ones. interface could be modified as public or no modifier; as having no modifier it is considered as an interface used only in the current package.
Interface contains two parts: constants and abstracted methods. in java 8, it is allowed to declare implemented method, but it must be static.
Interface variables and methods, may omit modifier; by default they will be understood as public abstracted methods and "public static final " respectively.
When an interface need adding new abstract methods; it is best to extend from it, thus it won't break existing code. so an interface could extends from many other interfaces. please, an interface cannot implement other interfaces; it doesn't make any sense, for interface cannot instantiate those inherited abstract methods.public interface myinterface{ double PI = 3.14; void setRidus(double r); double getRidus(); }
Interface gives a chance of carrying out multiple inheritances in Java. It describes that its sub-class is a type like the Interface. So two classes implementing the same interface, could be considered as having a similar type. I use the wording, "something like" relationship, for I don't think it is exactly same as the consequence due to "extends".
Inheritance
Inheritance describes a IS-A relationship between two objects. For instance, an Apple is a Fruit, thus Fruit could be designed as a super-class, and Apple as its sub-class. The common attributes and behaviors among fruit could be inherited by Apple class. Sub-classes can inherit fields and methods from the interface, abstract class or normal class.
The instance method could be overridden in sub-class and class fields and method could be hidden in the subclass due to shadowing.
Instance method: can be overridden in sub-class.
Explicitly using @override to instructs comelier.
Overriding convention: the method must have the same signature, parameters(including numbers) and return type. A overriding method can also return a sub-type of the super class, This is also called a co-variant return type. However, for the primitive return types, they must be the same.
Class method: cannot be overridden by instance methods in a sub-class; however it can be hidden by a static(class) method in the sub-class, if sub-class declare the same signature as the the class method in the super-class.
Please note: a sub-class instance method cannot override a static class-method in the super-class(private method is an exception, for it cannot be inherited); only static method in the sub-class hides another static method in the super class. Otherwise you will get a compiling error.
The same principle: a sub-class static method cannot override a super-class instance method; otherwise you will get a compiler error.
Overloaded methods are differentiated by the number and the type of the arguments passed into the method. the return type differences have no matters with determining overloading or not.
Note: In a subclass, you can overload the methods inherited from the super-class. Such overloaded methods neither hide nor override the super-class methods—they are new methods, unique to the subclass.
Method Overriding:
Methods having the same signatures, the same argument, but could be distinguished by the return types. Return the same primitive type OR Return a class or Interface type, following a co-variant return type. In addition, access modifier should be the same.
Overriding distinguished by 1) the inheritance, and then must be instance methods. 2) then the same signature and argument(type, sequence and number) 3) return type must be same for the primitive; for the reference type it must be the sub-types. 4) access-modifier must be the same as the super-class.
Overriding is only relevant to the instance methods. Instance fields cannot be overridden, but only hidden due to shadowing. The same principle for the class methods and fields, they are not able to be overridden.
Method cannot be overridden:
Private method cannot be inherited, so it cannot be overridden. For the sub-class, it is a new method.
Final method in the super-class cannot be overridden, just like final class cannot be extended.
Static method cannot be overridden, but could be hidden in the sub-class.
Please note: hidden fields/static methods are rarely used.
Virtual Method Invocation:
This principle is only relevant to the overridden instance methods. For hidden class methods, they can be directly referred by real class name; however, for overridden methods are referred is determined by the actual class used to instantiate the reference variable. Meaning that, variable type could be declared as a super-class, but in the run-time it could be instantiated as any sub-class object. So invoking overridden instance methods, requires to watch out the object class type.
JVM calls the appropriate method for the object that is referred to in each variable. It does not call the method that is defined by the variable's type. This behavior is referred to as virtual method invocation and demonstrates an aspect of the important polymorphism features in the Java language.
Super keyword:
For overridden instance methods, the overridden super-class instance methods can be accessed by the super keyword.
Overriding distinguished by 1) the inheritance, and then must be instance methods. 2) then the same signature and argument(type, sequence and number) 3) return type must be same for the primitive; for the reference type it must be the sub-types. 4) access-modifier must be the same as the super-class.
Method cannot be overridden:
Final method in the super-class cannot be overridden, just like final class cannot be extended.
Static method cannot be overridden, but could be hidden in the sub-class.
Please note: hidden fields/static methods are rarely used.
Virtual Method Invocation:
This principle is only relevant to the overridden instance methods. For hidden class methods, they can be directly referred by real class name; however, for overridden methods are referred is determined by the actual class used to instantiate the reference variable. Meaning that, variable type could be declared as a super-class, but in the run-time it could be instantiated as any sub-class object. So invoking overridden instance methods, requires to watch out the object class type.
JVM calls the appropriate method for the object that is referred to in each variable. It does not call the method that is defined by the variable's type. This behavior is referred to as virtual method invocation and demonstrates an aspect of the important polymorphism features in the Java language.
Super keyword:
For overridden instance methods, the overridden super-class instance methods can be accessed by the super keyword.
Method overloading:
methods they have same method signatures, but different input parameter types or numbers of parameters.
Note: In a subclass, you can overload the methods inherited from the super-class. Such overloaded methods neither hide nor override the super-class methods—they are new methods, unique to the subclass.
Note: Overloaded methods should be used sparingly, as they can make code much less readable.
Why static method cannot be overridden?
Static methods cannot be overridden because method overriding only occurs in the context of dynamic (i.e. run-time) lookup of methods. Static methods (by their name) are looked up statically (i.e. at compile-time).
Why static method cannot be overridden?
Static methods cannot be overridden because method overriding only occurs in the context of dynamic (i.e. run-time) lookup of methods. Static methods (by their name) are looked up statically (i.e. at compile-time).
Actually, you might have noticed that as using a static method, you may directly qualify it by using the class name; this won't confuse compiler at compiling time; it exactly know which method should be referred. however, for the instance method, then it has a dynamic selection issue as in a run time.
Overriding vs Overloading
in sub-class you may overload an inherited method from the super-class. This is not hiding or overriding; but just a new instance method.
Overriding is a concept associated with the inheritance; which gives sub-class freedom to redefine the behavior locally but keeping consistency with the super-class on the common behaviors.
Overloading follows a similar idea keeping the same method signatures, but it varies on the input arguments's numbers, and their types. the return type doesn't really a matter to distinguish.
Polymorphism
for instance, a woman may have different roles, as a mother, sister, daughter, or an aunt. So on the scenarios she may have different behaviors.
Inheritance and overriding offers Polymorphism.
The Java virtual machine (JVM) calls an appropriate method for the object that is referred to in each variable. It does not call the method that is defined by the variable's type. This behavior is referred to as virtual method invocation and demonstrates an aspect of the important polymorphism features in the Java language.
Final a method and a Class
Declaring some or all of a class's methods final, to indicate that the method cannot be overridden by sub-classes; Declaring an entire class final — this prevents the class from having sub-classes. This is particularly useful, for example, when creating an immutable class like the
String
class.
Object Class
java.lang.object is the root for the all java class. it offers several useful methods.
- protected Object clone() throws CloneNotSupportedExceptionCreates and returns a copy of this object. object must implements clonable interface.
- public boolean equals(Object obj)Indicates whether some other object is "equal to" this one. You have to note this equals only use "==", so it may not fit what your need, so you may override it.
- protected void finalize() throws ThrowableCalled by the garbage collector on an object when garbagecollection determines that there are no more references to the object.
- public final Class getClass()Returns the runtime class of an object.
- public int hashCode()Returns a hash code value for the object.
- public String toString()Returns a string representation of the object.
The hashCode() Method
The value returned by
hashCode()
is the object's hash code, which is the object's memory address in hexadecimal. By definition, if two objects are equal, their hash code must also be equal. If you override the equals()
method, you change the way two objects are equated and Object
's implementation of hashCode()
is no longer valid. Therefore, if you override the equals()
method, you must also override the hashCode()
method as well.
Abstract Class
Abstract class is a common place for a group of classes to put their common attributes and methods; and declaring common abstracted behaviors.
When an abstract class is subclassed, the subclass usually provides implementations for all of the abstract methods in its parent class. However, if it does not, the subclass must also be declared
abstract
.
Unlike interfaces, abstract classes can contain fields that are not
static
and final
, and they can contain implemented methods.
Abstract class may implement interfaces; however unlike concrete classes, an abstract class has no need to implement all of abstracted method defined in the interfaces. it may even don't implement any abstracted method defined in the interface.
I think this is not hard to understand. Abstract class is abstract like an interface; the most important is all of its sub-classes have to implement its interface methods.
Abstract Class vs Interface
abstract class define or say abstract common features and behaviors of classes, and in one place. that is why it may contains implementation of the methods, while leaving sub-classes the freedom to implement locally abstracted methods.
So Abstract class may contain instance or class variables and instance and/or class methods.
The interface, only contains class variable; and public methods.
Exception:Checked exception means you need to check it.
Unchecked exception means you don't need to check it.
All java exceptions and errors are Throwables.
Checked exception is extended from "Run-time-Exception"
Unchecked exception is extended from "Exception"
If checked exception is not caught, then you need to 'throws' it.
When an error occurs within a method, the method creates an object and hands it off to the runtime system. The object, called an exception object, contains information about the error, including its type and the state of the program when the error occurred. Creating an exception object and handing it to the run-time system is called throwing an exception.
Generics:
Java generics is introduced from Java 5. The basic purpose behind using generics is to enable you to mark your intent of using a class, method, or interface with a particular data type. Generics add compile-time safety to collections. By this way, a type inconsistency may be found in a early time, rather than in the run time. Generics can be applied on a class, an interface, a method, and even a constructor. They are called generic classes, generic methods, or generic constructors.
Java generics is introduced from Java 5. The basic purpose behind using generics is to enable you to mark your intent of using a class, method, or interface with a particular data type. Generics add compile-time safety to collections. By this way, a type inconsistency may be found in a early time, rather than in the run time. Generics can be applied on a class, an interface, a method, and even a constructor. They are called generic classes, generic methods, or generic constructors.
The key for Generics is to declare formal type parameters at a class or method level. Type parameter follows a naming convention: using <Single Capital Letter>. A formal type parameter can be replaced by actual data type in the compiling time, but erased in the runtime.
For a generic class, formal generic types should be declared after class name;
For a generic method, formal generic type should be declared after access modifier before the return type. This is important, otherwise compiler may don't know what's return type.
Actual type can be inferred by the compiler .
for class generics : type parameter inferred from the type argument.
for method generics: type parameter inferred from the real data type.
The type variable can be presented by a wildcard(?); it means it could be any types. Wildcard can be extended from a upper bound type(extends) or a super type of a lower bound type(super).
for class generics : type parameter inferred from the type argument.
for method generics: type parameter inferred from the real data type.
The type variable can be presented by a wildcard(?); it means it could be any types. Wildcard can be extended from a upper bound type(extends) or a super type of a lower bound type(super).
Collection:
A collection is a container, storing a group of elements(objects).
Java collection framework support three types of collections: Set, List, Queue and Map.
Set: HashSet, LinkedHashSet and TreeSet
List: ArrayList, LinkedList
Queue: ArrayDeque
Queue: ArrayDeque
Map: HashMap, LinkedHashMap, and TreeMap
Linked: keep insertion order, not sorted
Hash: keep no insertion order, not sorted
Tree: keep no insertion order, sorted.
Set: unique, element must be comparable.
Map: keep key value pairs.
Linked: keep insertion order, not sorted
Hash: keep no insertion order, not sorted
Tree: keep no insertion order, sorted.
Set: unique, element must be comparable.
Map: keep key value pairs.
How elements in the are sorted? here you may hard code.
1) using default, element.compareTo(another element) method; the class need implements java util Comparable interface.
2) using costumer defined external Comparator, which implements implements java util Comparator java.io.Serializable,
public interface Comparator{
public int compare(Object element1, Object element2);
public boolean equals(Objects element);}
Map: (key, value) one to one relationship.
HashMap : not synchronized. null key and null value
HashTable: synchronized. not allowed null key and null value.
Can you put more than one class in one java file?
Yes. the only limitation is you only can have one public class. the rest must be default access.
Super-class has explicitly declare a constructor with arguments, then JVM will automatically provide no non-argument for it. So you need to watch out here, as define a non-argument in the sub-class extended from it. It will cause a compiling error, for the super-class has no a non-argument constructor defined yet.
Is able to declare public static void main(String args[]) in other access modifier?
no, you must declare main class as public. you cannot use protected, default modifier, and private.
final public static void main(String args[])
final means here for the static method cannot be shadowed.
final means for the instance method, it means the method cannot be overridden.
java constant declaring: must be final static int xxx = yyy; the constant must be initialized as declaring, otherwise it will give a compiling error. so what is a constant is? it should be a value that commonly shared by the instances, and it cannot shadowed.
All java arrays are objects, int[] array={1,2,3}; array instanceof Object = true.
Can you put more than one class in one java file?
Yes. the only limitation is you only can have one public class. the rest must be default access.
Super-class has explicitly declare a constructor with arguments, then JVM will automatically provide no non-argument for it. So you need to watch out here, as define a non-argument in the sub-class extended from it. It will cause a compiling error, for the super-class has no a non-argument constructor defined yet.
Is able to declare public static void main(String args[]) in other access modifier?
no, you must declare main class as public. you cannot use protected, default modifier, and private.
final public static void main(String args[])
final means here for the static method cannot be shadowed.
final means for the instance method, it means the method cannot be overridden.
java constant declaring: must be final static int xxx = yyy; the constant must be initialized as declaring, otherwise it will give a compiling error. so what is a constant is? it should be a value that commonly shared by the instances, and it cannot shadowed.
All java arrays are objects, int[] array={1,2,3}; array instanceof Object = true.
If you have a Object object = null; what happens as System.out.println(obejct)?
It will print out 'null'; It won't cause null pointer exception, for there is no operations on the null.
What happens when you print out b.i?
class A{
private int i = 10;
public void f(){}
public void g(){}
}
class B extends A{
public int i = 20;
public void g(){}
}
public class C{
A a = new A();//1
A b = new B();//2
}
No you cannot. for b has been declared as Type A, for the A the i is a private field, not accessible.
static method cannot access instance fields, but only static fields.
instance method can access class field and instance field both.
Keyword final
It can be used to modify class, variable, and method. I think it try to define something it is final; not allowed to be changed.
a final class cannot be extended; a final variable cannot be hidden(??? i didn't see this.), anyway it will be constant; it cannot be assigned a new value; a final field must be initiated as declaring it; a final method cannot be overridden.
final modifier cannot be applied on the constructor, for constructor cannot be inherited.
char, byte, short int are int type, but you need to watch out type narrowing, meaning that when assigning a int number to byte, char, short; requiring casting.
Keywork transient
transient keyword, telling JVM the modified variable is not serialize-able/persisted.
No comments:
Post a Comment