Please enable JavaScript.
Coggle requires JavaScript to display documents.
Java SE - Coggle Diagram
Java SE
ArrayList
e.g.
List<String> museums = new ArrayList<>(1);
the ArrayList is declared with an initial capacity of one element, it is free to expand
List<String> tools = new ArrayList<>( );
List<Integer> pennies = new ArrayList<>();
pennies.add(3);
pennies.add(2);
pennies.add(1);
pennies.remove(2);
System.out.println(pennies);
[ 3, 2 ]
zero-based indexes
add
tools.add("hammer"); tools.add("nail");
get
System.out.println(tools.get(1));
size
list.size( )
While it isn’t recommended to use generics on only the left side of the assignment operator, this is allowed. It just gives a warning. 9.48
18 type
raw
generic
just diamond operator
with specific type in it
left side
right side
rules:左边不能是空钻,两边类型需要相同
Lambdas
Lambdas use deferred execution and can be run elsewhere in the codebase.
可以没有形参 a lambda can have zero parameters, a Predicate cannot.
predicate
A Predicate is defined as a type mapping to a boolean
必须有形参
有花括号才能写return return is only allowed when the brackets are present
当写花括号时,必须写return和分号;
Predicate<Integer> ip = i -> i != 0;
Predicate<Integer> ip = i -> { return i != 0; }
The type in the lambda must match the
generic
declared on the Predicate
Predicate<String> pred =
___
—> true;
e.g.
Predicate clear = c -> c.equals("clear"); System.out.println(clear.test("pink"));
false
the generic is omitted, it is treated like a Predicate of type Object.
return is only allowed when the brackets are present
有花括号才能有return
https://www.evernote.com/shard/s308/sh/6b4ae3ac-8998-4ff4-9cb5-386a6267239a/dcef8dc76b173d8f19334a9a1f38dabf
creating a lambda with
only one parameter
, there are a few variants.
Predicate<String> pred1 = s —> true;
Predicate<String> pred2 = (s) —> true;
Predicate<String> pred4 = (String s) —> true;
写形参类型就必须有括号
Predicate<String> pred3 = String s —> false;
Wrong
Iheritance and polymorphism 7
11 conditions of override
virtual method (3 non)
non-final
if you want to override a method with final, with same signature. You will get an compile error
子类 overriding method 可以加 final。 overridden method 不能加 fianl
compile error
non-private
( can only see this method in its own class or compiler error, depends on where is main() ) ( subclass make its own method, but you can't use superclass's ref to refer this method out of superclass)
if private, you can’t see it. you can write a method with same signature without compile error
https://repl.it/@bjetc5/private-final-vs-public-final#Main.java
thanks for the private, or the final will give you an error. the private make you can't see it.
7 11
( if you use superclass's ref points to an subclass's obj in superclass then it will run method in the superclass,as there is no overriding relation, it just run the method in the class)
hide method used depends on calling location
子类中与父类private method重名的method不是override,不会报错,会当成子类中的新函数处理. 这种情况只有pure subclass obj(ref's type 是subclass的情况)才能调用子类中的同名函数。如果frso。 reference's type是father class的那么会报错,因为没有override关系。看不见private
non-static
A static method cannot override an instance (non-static) method and vice versa
static -- static hiding instance -- instance override
method with same signature in the subclass is called hiding
compile error
the return types of an overridden method must be
covariant
same for primitive type
subclass or same for returning Obj
Overriding method throw narrower exception
or not compile
2) Rule: If the superclass method does not declare an exception, subclass overridden method
cannot
declare the
checked exception
but
can declare
unchecked exception
.
same method signature
name
number of parameter
type of parameter
if two methods have different signature, the relation is not override
7.35 7.37
Usually, method overloading happens inside a single class, but a method can also be treated as overloaded in the subclass of that class — because the subclass inherits one version of the method from the parent class and then can have another overloaded version in its class definition. 7.44
如果signature相同,则被认定为 试图override,那么需要去满足其他override的条件,modifier更宽,return type相同或是子类,exp更窄等等
has wider modifier
obj reference assign and casting
cast
upcasting 抽象化——narrow
Upcasting
narrows
the list of methods and properties available to this object
frso
Father ref —> Son obj
只能调用父类的变量
父类中没有的函数,只有子类中有,frso不能调用
父类中的普通函数不是被继承就是被重写,private函数只有在类中可见
override函数 调用的是子类的函数
downcasting 具体化 —— extend
本质 the ref's obj need to be the instance of that class to downcast to it 你需要知道这个obj到底是什么
7.29
downcast 只能cast到 本身最底层 否则出现ClassCastException
((Son)shbd).play();
// java.lang.ClassCastException: class Father cannot be cast to class Son
((Son)frso).play();
play fortnite
Son sfq = (Son)new Father();
// Father cannot be cast to Son. it compiles, but throw an exception java.lang.ClassCastException: class BasicPoints.Father cannot be cast to class BasicPoints.Son
String checkZipper = (String)new Object();
// CastClassException
the outer ( ) is must to make sure downcast run first, if not then .play( ) will run first.
Upercast 可以直到Object
((Father)new Son()).play();
upcasting
play fortnite
往宽了cast随意, 往窄了down cast,只能到自己本身那一类
从父类引用(down)cast到原本类的引用指向对象,只能用于确实属于这个类的引用(check by instanceof)
if (fluffy instanceof Cat) { ((Cat) fluffy).meow() }
The object type determines which attributes exist in memory,
while the reference type determines which attributes are accessible by the caller.
ref assign
question: 7.25
https://www.evernote.com/l/ATThq9hwxeND2KqcABxzj100Y9BMJR5Vr50/
能够指向你,( AAA aa = new CoreClass )那么AAA可以是CoreClass 的
同类,父类,接口,抽象类, 祖宗类Object
An object can be assigned to a reference variable type that it inherits
但是不能是子类
左宽 <= 右窄
不用加( )
否则就要cast 加( )
abstract claas
自己不能实例化,但可以有构造函数,让继承类构造函数使用
普通类
必须实现所有继承下来的
抽象函数,抽象类继承抽象类可以不实现抽象函数
可以有concrete method就像普通类那样,但不用像interface那样标明default
抽象类class 前必须标明abstract,抽象函数method必须标明abstract
Unlike interface, abstract class can have
final
concrete
method, just like a common class
It can have static method
A concrete class can extend an abstract class, while an abstract class can extend a concrete class
for abstract class, abstract method can use protected, but not private.
The abstract method in abstract class can only set a visibility modifier, one of public or protected
Non-abstract common class can't have abstract method. Only interfaces and abstract classes can include abstract methods.
Can have a runnable main() method
interface
modifier of method
method
2 (public) static
static methods must have a body
1 (public) abstract
don’t have a body
All abstract interface methods are implicitly public
No private, No protected. just public
final is not allowed
3 (public) default
These methods allow developers to update older classes with a newer version of an interface without breaking functionality in the existing classes 更新接口时不用改老类
4 strictfp
variable
public static final
Java allows multiple inheritance using interfaces.
one class implements several interfaces
having one class extend two interfaces that both define the same default method signature leads to a compiler error, unless the class overrides the method. 7.37
实现两个接口,都有相同的default method,那么class里必须对这个method override。这样才不会产生歧义(到底继承了哪个?)
default method doesn't need to be overridden by subclass, however, if the subclass implements two interfaces with two same name default name, then override method is must.
接口中的默认函数不需要继承。但是如果是多重继承,且两个接口中的默认函数同名,那么这时这个同名的默认函数需要被重写override,否则不知道该用哪个
verb
class
extends
class
class
implements
interface
interface
extends
interface
One class can extends a (abstract) class and implements an interface at the same time. extends abstract class need to be first.
Instantiate?
Lambda
ref.test(xyz)
Interface ref = new subClass()
default method
abstract method
variable and static method hiding
variable
if you define a same name variable in child class, then the inherited one can't be seen
static method
If a subclass defines a static method with the same signature as a static method in the superclass, then the method in the subclass hides the one in the superclass.
static method属于类,而不是对象。调用静态函数需要类名,或者看在哪个类中。如果用对象ref调用static method也允许,这种情况看ref的类型是什么,一个frso会调用父类的静态函数
Array
Instantiation of an Array in Java
String sheep[] = new String[3];
int a[]={33,3,4,5};
用的是大括号
要么给出大小,要么用大括号实例化,不能两样都写
装size的中括号只能放在type后面,不能放new后面
Syntax to Declare an Array in Java
dataType[] arr
dataType []arr
dataType arr[]
[ ] 不能在dataType前面
length
arr.length
Declare Multidimensional Array
dataType[][] arrayRefVar; (or)
dataType [][]arrayRefVar; (or)
dataType arrayRefVar[][]; (or)
dataType []arrayRefVar[];
定义多维数组时,第一维大小必须给出,其他的optional
When instantiating a multidimensional array, it is legal to leave out the size for later dimensions of a multidimensional array, the first one is required.
维度与维度用中括号隔开,中间没有逗号
String
三个接口
三个同类
String
Create
String a = "welcome"
Create a string in string constant pool
String b = new String("welcome")
Create a string in heap memory
By char[ ]
char[] ch={'j','a','v','a','t','p','o','i','n','t'}; String s=new String(ch);
Immutable
final
method will create new string
Methods
str.length( )
only StringBuffer and StringBuilder
reverse( )
insert( )
only String has this method
startsWith()
replace( 2p )
common method
char charAt(int index)
int codePointAt(int index)
int compareTo(String anotherString)
Compares two strings lexicographically.
逐个比较字符串中的字符,char化作数字做减法
字符char可依照unicode化作数字做数字运算
如果长度相同,那么caller字符串长度-arg字符串长度
int compareToIgnoreCase(String str)
String concat(String str)
boolean contains(CharSequence s)
boolean contentEquals(CharSequence cs / StringBuffer sb)
static String valueOf( int i / long l / float f / double d / boolean b / char c / char[ ] data / Object obj )
static String valueOf(char[] data, int offset, int length)
the caller's value can't stay, it just return the value of argument as string
char[] toCharArray()
String trim()
trim leading and trailing space
String toUpperCase / toLowerCase( / Locale locale)
String toString()
return itself
String substring(int beginIndex, int endIndex)
CharSequence subSequence(int beginIndex, int endIndex)
suitable for String, StringBuffer, StringBuilder
boolean startsWith(String prefix, int toffset)
String[] split(String regex, int limit)
String replace(CharSequence target, CharSequence replacement)
StringBuffer
thread safe and supports multiple threads
synchronized
two threads can't call the methods of StringBuffer simultaneously
less efficient than StringBuilder
StringBuilder
not thread safe
StringBuilder does not support multiple threads
StringBuilder teams = new StringBuilder("333");
https://www.javatpoint.com/StringBuilder-class
replace(3p)
non-synchronized
more efficient than StringBuffer
methods
https://www.evernote.com/l/ATS6lpkqjnVMHrkk7PSBRiLHT13mck6Y_zE/
https://www.dropbox.com/s/wb4p0x3twdtxzku/method%20comparison%20between%20String%20StringBuffer%20StringBuilder.xlsx?dl=0
Method (6)
Structure
2 static/class or instance
static import 30
static imports can be used to reference both variables and methods
static imports are used with members of the class, not a class name.
access
static method cannot access instance variable or method
34
instance method can access static variable or method
3 return type
Need to be before method name
type transfer from return
5 ( Input ) /Signature
parameter type
parameters
varargs
String varargs, which can be an
array
of String values or
zero
or more
individual
String values.
only one and placed in the last
a null value does not have a type and can be assigned to any reference variable.
7.42
Rules
Pass by value
7 { statements }
2 final or not
blank final variable
initialize in instance initialized block or constructor only
blank static final variable
initialize in static block only
1 access modifier
public
private
protected
package private
4 method name /Signature
start with a letter, the dollar $ symbol, or underscore _
signature
The signature of a method is:
Its name.
The number and types of its parameters, in order.
6 throw exp
constructor
Loading order
1 super() or this ()
a constructor can only call this() or super() on the first line of the constructor, but never both in the same constructor.
only constructors can call super()
super() is added in each class constructor automatically by compiler if there is no super() or this().
If a constructor call is not the first line of the RainForest() constructor, the compiler inserts the no-argument super() call.
0 static block
7.27
2 instance initialization block
3 its statements
if and only if a class does not declare a constructor, a default no-argument constructor is automatically inserted by the compiler.
constructor doesn’t have return type ( if there is a void, it is not a constructor )
Super class constructor with parameter without no-argument constructor
the subclass need to define one or more constructor
Just must to write super( p1 p2…) in its own constructor yourself
6.45 7.27 7.29
构函形参可以不同,但super内的形参必须和父亲构函形参保持一致,super(x,y)
a subclass extends that supper class, the subclass has a constructor, you need to write super(...) or the compiler will insert a default super( ) . this will happen in the first line in the constructor. the ting is that the superclass doesn't have super( ) in this case, so you must write super ( with sth super can eat ) yourself. the subclass's input is optional
overload
Need
Same method name
Different number of parameter or different type of parameter
Don’d need
Different return type
overload vs override
signature
overriding method in subclass need to have same signature with superclass
A class cannot contain two methods with the same method signature, even if one is static and the other is not.
class
overload can happened in same class or subclass , while override happened between subclass and superclass (two class)
overload method in subclass
just like the overload method in the same class, it is written in the subclass. it has the same name, but different signature. not override method
Exception 8
Java.lang.Throwable
Exception
Checked exception
checked at compile-time
Rule: By default, Checked Exceptions are not forwarded in calling chain (propagated).
不能自行传递出来,需要用throws声明
Exception Handling is mainly used to handle the checked exceptions
Exception is a checked exception and must be handled or declared by the method in which it is thrown.
if one class extends Exception class then it is treat as a checked exception class.
Unchecked exception
checked at runtime
inherit RuntimeException
By default Unchecked Exceptions are forwarded in calling chain (propagated).
exception occurs in m() method where it is not handled,so it is propagated to previous n() method where it is not handled, again it is propagated to p() method where exception is handled.可以自行传递
If there occurs any unchecked exception such as NullPointerException, it is programmers fault that he is not performing check up before the code being used.
like x/0 , nullpointer , class type cast error
Error
irrecoverable
An Error often indicates a failure of the JVM which cannot be recovered from.
A Java application tends to only throw an Error when the application has entered a
final, unrecoverable state
. Options A and C are incorrect. These types of errors are
common and expected in most software applications
, and
should not cause the application to terminate
. Option B uses the word
temporarily
, meaning the network connection will come back. In this case, a
regular exception
could be used to try to
recover
from this state. Option D is the correct answer because running out of memory is usually
unrecoverable
in Java. 8.48
5 key words
try 1-n
a block where we should place exception code
Multiple try block
catch 0-n
Multiple catch blocks
如果有多个exception,且有多个catch block, 那么只能抓住一个,之后运行rest code
multiple catch blocks need to follow order from specific to general, or there will be an error
must be preceded by try block
If the exception is not caught, then the rest of code in catch block won’t run.
If you are
calling
a method that declares an
checked exception
, the
calling**
method( like main method )
must** either caught or declare the exception.
Cheched exception (including exception) must be caught or throws
unchecked exceptions can be optionally handled or declared. 也可以,但不是必须的
catch 需要写在 finally前面,否则编译报错
finally 0-1
肯定是要执行的 It is executed whether an exception is handled or not
the code behind it can’t run if the exp is not caught
Only one. Can’t run if program exit
如果try, catch和finally都抛出意外,那么try, catch里的exception drop, finally里的exception传递给caller
如果try里的exp catch住了,那么先运行catch block里的内容,后运行finally里的内容
先finally 后try return
!
throw
用来扔自定义的exception
throws
用来传递checked exception出嵌套函数 (声明这个函数可能会抛出意外)这样checked exception就能在嵌套函数中传递了
A try block must include either a catch or finally block, or both.
try catch finally block里如果抛出异常,则后面的statement不会再运行,会跳转到handler或throws给caller. finally是必须要运行的
Flow control