[关闭]
@gone 2014-10-05T16:10:04.000000Z 字数 8824 阅读 1499

Java Basic

OOP DS Java


>>> indicates unsigned right shift
e.g,
22 = 0b00010110

  1. 22>>>1
  2. 00001011
  3. -22>>>1 //-22 补码表示1101001
  4. 01110100

TypeCast

  1. public class TypeCasting {
  2. public static void main(String[] args) {
  3. Father father = new Son();
  4. /*
  5. * the `father` reference to a Son object, but based on its type(Father), it's only visible to `show(), show_father()` functions, in the meanwhile, `show()` has been overriden.
  6. */
  7. father.show(); // output : `This is son`
  8. father.show_father(); //output : `This is father`
  9. Son s = new Son();
  10. s.show_father(); // output : `This is father`
  11. s.show_son(); // output: `This is son`
  12. father = (Father) father; // cast to Father, but the object it references to is still type of Son
  13. father.show(); //output: 'This is Son'
  14. father.show_father(); // output : `This is father`
  15. }
  16. }
  17. class Father {
  18. public int name = 0;
  19. public void show() {
  20. System.out.println("This is father");
  21. }
  22. public void show_father() {
  23. System.out.println("father!");
  24. }
  25. }
  26. class Son extends Father {
  27. public int name = 1;
  28. public void show() {
  29. System.out.println("This is Son");
  30. }
  31. public void show_son(){
  32. System.out.println("Son!");
  33. }
  34. }

JAVA IO

Common Java Data Structure

First of all, "Collection" and "Collections" are two different concepts. As you will see from the hierarchy diagram below, "Collection" is a root interface in the Collection hierarchy but "Collections" is a class which provide static methods to manipulate on some Collection types.
Collection and Collections

Class Hierarchy

Interfaces Hashtable Resizable Array Tree Linked List Hash table + Linked List
Set HashSet TreeSet LinkedHashSet
List ArrayList LinkedList
Queue
Map HashMap TreeMap LinkedHashMap

Java Class Hierarchy

Principles of OOPs (Reference)

Encapsulation [ɪn,kæpsə'leɪʃən]

Also known as "Data Hiding"

he encapsulation is achieved by combining the methods and attribute into a class. The class acts like a container encapsulating the properties. The users are exposed mainly public methods.The idea behind is to hide how thinigs work and just exposing the requests a user can do.

Inheritence

Inheritance is the property which allows a Child class to inherit some properties from its parent class. In Java this is achieved by using extends keyword. Only properties with access modifier public and protected can be accessed in child class.

  1. public class Parent{
  2. public String parentName;
  3. public int parentage;
  4. public String familyName;
  5. }
  6. public class Child extends Parent{
  7. public String childName;
  8. public int childAge;
  9. public void printMyName(){
  10. System.out.println(“ My name is “+ chidName+” +familyName)
  11. }
  12. }

What is multiple inheritance and does java support?
If a child class inherits the property from multiple classes is known as multiple inheritance.
Java does not allow to extend multiple classes but to overcome this problem it allows to implement multiple Interfaces.

Polymorphism [,pɒlɪ'mɔːfɪz(ə)m]

The abiltiy to define more than one function with the same name is called Polymorphism. In Java,C++ there are two type of polymorphism: compile time polymorphism (overloading) and runtime polymorphism (overriding).

overloading

  1. Class BookDetails{
  2. String title;
  3. String publisher;
  4. float price;
  5. setBook(String title){
  6. }
  7. setBook(String title, String publisher){
  8. }
  9. setBook(String title, String publisher,float price){
  10. }
  11. }

overriding

  1. class BookDetails{
  2. String title;
  3. setBook(String title){ }
  4. }
  5. class ScienceBook extends BookDetails{
  6. setBook(String title){} //overriding
  7. setBook(String title, String publisher,float price){ } //overloading
  8. }

Abstraction

Abstraction is way of converting real world objects in terms of class. For example creating a class Vehicle and injecting properties into it. E.g

  1. public class Vehicle {
  2. public String colour;
  3. public String model;
  4. }

The difference between Abstraction and Encapsulation

Encapsulation is a strategy used as part of abstraction. Encapsulation refers to the state of objects - objects encapsulate their state and hide it from the outside; outside users of the class interact with it through its methods, but cannot access the classes state directly. So the class abstracts away the implementation details related to its state.

Abstraction is a more generic term, it can also be achieved by (amongst others) subclassing. For example, the class List in the standard library is an abstraction for a sequence of items, indexed by their position, concrete examples of a List are an ArrayList or a LinkedList. Code that interacts with a List abstracts over the detail of which kind of a list it is using.

Abstraction is often not possible without hiding underlying state by encapsulation - if a class exposes its internal state, it can't change its inner workings, and thus cannot be abstracted.

What is association?
Association is a relationship between two classes. In this relationship the object of one instance perform an action on behalf of the other class. The typical behaviour can be invoking the method of other class and using the member of the other class.

  1. public class MyMainClass {
  2. public void init(){
  3. new OtherClass.init();
  4. }
  5. }

What is Aggregation?
Aggregation has a relationship between two classes. In this relationship the object of one class is a member of the other class. Aggregation always insists for a direction.

  1. public class MyMainClass{
  2. OtherClass otherClassObj = new OtherClass();
  3. }

Modifiers in Java (Reference)

Accessibility Modifiers

Java has several modifiers keywords public, protected, private, the last modfier keywords is null or by default(no explicit).

Java's access level can be divided into two parts:
1. Access Level for class
2. Access Level for members(fields and methods)

For 1
public class means this class can be accessed outside, class by default means it's private (only visible within package);

For 2

There're 4 levels for members: public, private, protected, package-private(no explicit modifier). The following table summarizes the access levels of each keyword:

keyword class package subclass world
public yes yes yes yes
protected yes yes yes no
no modifier yes yes no no
private yes no no no

Other Modifiers/Keywords

  1. static
  2. abstract
  3. final
    1. Almost same as constant
  4. synchronized
  5. transient
    • If some of the properties of a class are not required to be serialized then the varaibles are marked as transient. When an object is deserialized the transient variables retains the default value depending on the type of variable declared and hence lost its original value.
  6. native
  7. throw

    • Throw keyword is used to throw the exception manually. It is mainly used when the program fails to satisfy the given condition and it wants to warn the application.The exception thrown should be subclass of Throwable.
      1. public void parent(){
      2. try{
      3. child();
      4. }catch(MyCustomException e){ }
      5. }
      6. public void child{
      7. String iAmMandatory=null;
      8. if(iAmMandatory == null){
      9. throw (new MyCustomException("Throwing exception using throw keyword");
      10. }
      11. }
  8. volatile
    • In general each thread has its own copy of variable, such that one thread is not concerned with the value of same variable in the other thread. But sometime this may not be the case. Consider a scenario in which the count variable is holding the number of times a method is called for a given class irrespective of any thread calling, in this case irrespective of thread access the count has to be increased. In this case the count variable is declared as volatile. The copy of volatile variable is stored in the main memory, so every time a thread access the variable even for reading purpose the local copy is updated each time from the main memory. The volatile variable also have performance issues.

Pass by Value

Java is always pass-by-value. The difficult thing can be to understand that Java passes objects as references and those references are passed by value.

  1. Dog aDog = new Dog("Max");
  2. foo(aDog);
  3. aDog.getName().equals("Max");
  4. public void foo(Dog f) {
  5. f.getName().equals("Max"); // return true
  6. f = new Dog("Fif"); // the reference is changed
  7. d.getName().equals("Fif"); // return true
  8. }

Garbage Collection

What is responsiblity of Garbage Collector?

Answer Garbage collector frees the memory occupied by the unreachable objects during the java program by deleting these unreachable objects.
It ensures that the available memory will be used efficiently, but does not guarantee that there will be sufficient memory for the program to run. GC is a daemon thread behind the application, started and controled by JVM, it stops when all the non-daemon threads stop.

Define unreachable objects:An object becomes unreachable when no live thread can access it

One can request garbage collection to happen within the java program, but there's no guarantee that this request will be taken care of the JVM. So that Garbage Collection cannot be forced by any means.

Purpose of finallize()
The finallize() method should be overridden fo an object to include the clean up code or to dispose of the system resources to be done before the object is garbage collected.

There are several ways to request the garabge collection from JVM
1. Runtime.getRuntime().gc()
2. System.gc()

Exception

In Java, exception can be checked or unchecked. They both fit into a class hierarchy. The following diagram shows Java Exception classes hierarchy.

Red colored are checked exceptions. Any checked exceptions that may be thrown in a method must either be caught or declared in the method's throws clause. Checked exceptions must be caught at compile time. Checked exceptions are so called because both the Java compiler and the Java virtual machine check to make sure this rule is obeyed. Green colored are uncheck exceptions. They are exceptions that are not expected to be recovered, such as null pointer, divide by 0, etc.

If an exception can be properly handled then it should be caught, otherwise, it should be thrown.

Java Exception Class Hierarchy

Commonly Used Exceptions:
IllegalArgumentException
ArrayIndexOutOfBoundsException

JAVA 8

A、Interface changes with default and static methods
B、Functional interfaces and Lambda Expressions
C、Java Stream API for collection classes
D、Java Date Time API

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注