- We can call main() as a regular static method
- We can define multiple main() in difference classes
- Only ONE non-static top level public class inside a .java source code file https://www.quora.com/Why-there-is-only-one-public-class-in-java-source-code
public class A {
public static void main(String[] args) {
String[] strings = { "New York", "Boston", "Atlanta" };
B.main(strings);
}
}
class B {
public static void main(String[] args) {
for(int i=0; i<args.length; i++)
System.out.println(args[i]);
}
}
// javac *.java
// java A
// output:
NewYork
Boston
Atlanta
// Remember: Java's command line parameter args[0] is the first actual arg, but not the program nameLocal-Variable Type Inference:
Right hand side must be class constructor, or any method that return a value with certain type.
// before Java 10
String a = new String("hello");
// Java 10 and after
var a = new String("Hello");
var b; // error, cannot infer type
var c = null; // error, cannot infer typeLiteral has their default type when you using them without indicator.
var a = 10; // this is int
var b = 10L; // this is long
var c = 10.0; // this is double
var d = 10.0f; // this is floatJVM collect memory space occupied by the object if the space occupied by the object is no longer referenced by any variable.
Java Object auto managed by JVM in heap.
We have :
Byte, Short, Integer, Long, Float, Double, Character, Boolean
//e.g.:
Integer i_obj = new Integer(8963);
i_obj ++; // increase by 1, become 8964
Integer j_obj = new Integer("720"); // convert string to integer
j_obj ++; // increase by 1, become 721
// hint: This is deprecated in the LTS Java 13, but still works
int intVal = Integer.parseInt("831");
double dbVal = Double.parseDouble("10.1");Convert numeric object types into the corresponding primitive data types.
int three = new Integer(3).intValue();
double pi = new Double(3.14159).doubleValue();OR, Covert value represented string to numeric object:
Integer integerObj = Integer.valueOf(12);
Double doubleObj = Double.valueOf(12.4);-
Autoboxing Automatic conversion between the primitive types and their corresponding object wrapper classes. This is kind of syntax sugar.
-
Boxing - primitive types to wrapper class object
// Original: // Integer x = Integer.valueOf(1); Integer[] integerArray = { 1, 2, 3 };
-
Unboxing - reverse way
// Original: // Integer y = x.intValue(); System.out.print(integerArray[0] + integerArray[1] + integerArray[2]);
String str = new String();
String str2 = new String("dont know do what?");
String str3 = "dont know do what?"; // shorthand initializer, string literals- Strings are Immutable
For improving performance, JVM will check is there any string literals already exist in the pool, if yes then link the reference to a unique instance for the literals with the same character sequence.
String s1 = "abc";
String s2 = "abc";
String s3 = new String("abc");
System.out.println((s1 == s2)); // true
System.out.println((s1 == s3)); // false
System.out.println((s2 == s3)); // false
// Remember:
// using operator == is for checking the reference
// please use s1.equals(s2) for checking whether the contents are the same.str.compareTo(str2) | str.length() | str.charAt(index) | str.substring(x,y)
String str1 = "abc";
String str2 = "a";
int result = str1.compareTo(str2);
if ( result > 0)
System.out.println("str1 is greater than str2");
else if (result < 0 )
System.out.println("str1 is lesser than str2");
else if (result == 0 )
System.out.println("str1 is same as str2");
}
System.out.println(str1.length()); // print "3"
System.out.println(str1.charAt(1)); // print "b"
System.out.println(str.substring(1,2)); // print "bc"- str.toLowerCase()
- str.toUpperCase()
- str.trim() //string的前後空白刪除
- str.replace("abc", "a")
- str.split(" ", 0) // 0 means match as many times as possible, else means match k times; return String[]
... more (refer to https://course.cse.ust.hk/comp3021/notes/3-strings-full.pdf )
All static field in UML diagram is denote with Underline, ie: (getNumber():int)
public class A {
public static int i = 0;
}public class A {
static void getNumber(){
//...
}
}
A.getNumber();public class A {
public static final String str = "This var share over all instances.";
}- Static method can only access static variable
- Non static method can access instance variable/ static variable
Instance member variables (data member) have Default Values while method local variables need to be initialized before using them (otherwise compilation error occur).
// The default value of primitive data types
byte a = 0;
short s = 0;
int i = 0;
long l = 0L;
float fl = 0.0f;
double db = 0.0d;
char c = '\u0000';
boolean result = false;
// reference type default = null
String name = null;
int [] arrStr = null; // same, for arrayClass member variable also called Field.
Initialization can be done on declarations OR assign in constructor.
- constructor cannot be static
C++ provide default copy constructor of implicit call, while Java is NOT provide DEFAULT COPY Constructor.
class Complex {
private double re, lm;
// Normal parametrized constructor
public Complex(double re, double lm) {
this.re = re;
this.lm = lm;
}
// copy constructor, required to define it manually
Complex(Complex c){
System.out.println("copy constructor called");
re = c.re; // copying data
lm = c.lm;
}
}
public class Main {
public static void main(String[] args){
Complex c1 = new Complex(10,15);
// invokes copy constructor call
Complex c2 = new Complex(c1);
// This DOES NOT invole a copy constructor call
// but just re-assign the reference to another instance.
Complex c3 = c2;
}
}This cannot be overridden in any derived class of the A.
public class A {
public final Person func(){
// do something
}
}Keyword: extends
No multiple inheritance.
Only public inheritance is available.
Java does dynamic binding for overriding by default.
class A {
public void funX(){ System.out.print("X in A");}
public void funY(){ System.out.print("Y in A");}
}
class B {
@Override
public void funY(){ System.out.print("Y in B");}
}
A aRef = new B();
aRef.funY(); // it will call funY() in class B.- static method redefined is NOT overriding; when you redefined it in derived class, the original static method in superclass will be hidden.
- java.lang.Object is the ultimate parent of Java object.
- The toString() method CAN also be overridden.
A ref = new A();
Object obj = new Object();
// this line calling .toString() from java.lang.Object
// this will show className + "@" + ref_id
// e.g. A@15038e5
System.out.print(ref.toString());
// or this is equivalent to the code above
System.out.print(ref);
// This will output:
// java.lang.Object@b4c966a
System.out.print(obj);What is default/package accessibility?
- When *.java class file put in the same folder, they will share will package scope by default.
- or using keyword when they are not in the same folder: package name;
| Modifier | Class | Package | Subclass | World |
|---|---|---|---|---|
public |
Y | Y | Y | Y |
protected |
Y | Y | Y | N |
| no modifier (default) | Y | Y | N | N |
private |
Y | N | N | N |
Examples of access control in class variables and methods:
package p1;
public class C1 { // <--- beware, we use public class here
public int x; // everyone can access
int y; // only same package can access, e.g. C2
private int z; // only access within its class
}package p1;
public class C2 {
// can access C1
void method(){
C1 obj = new C1();
obj.x; // ok
obj.y; // ok
obj.z; // error
}
}package p2;
public class C3 {
void method() {
C1 obj = new C1();
obj.x; // ok
obj.y; // error
obj.z; // error
}
}- Default modifier to variable is quite similar to Public data member when you are coding in same single file.
Example in access control in class (default class, public class)
package p1
class C1 { // <--- beware, no any keyword here which means package scope.
public int x; // everyone can access
int y; // only same package can access, e.g. C2
private int z; // only access within its class
}package p1;
public class C2 {
// can access C1 variables/ method
// (to corresponding access keyword restricts)
}package p2;
public class C3 {
// cannot access C1 since it is "default class", we have different package
// can access C2 since it is "public class"
// (to corresponding access keyword restricts)
}-
Java don't have Private Class because no one can access it (even no one can call the constructor), so it is useless and non-sense.
-
Remember, class can only have Public / Default these TWO type of access modifier
WIP...
WIP...
https://www.geeksforgeeks.org/static-class-in-java/
Immutable object: object that are unable to changed once it is created
-
Something Tricky: We can use getter to change the data member of a class as below: The idea is that: It is still mutable IF the getter is passing out the actual reference of data member object.
public class ImmutableTest{ public static void main (String[] args){ A obj = new A(); Date a_date_ref = obj.getDateData(); a_date_ref.setYear(2020); // Now the date in instance A is changed. } } // How to deal with it? // We can create a new deep copy object of datamember then pass it out. // so that the modification outside the class will not affact the original one
The program return Compilation error:
{method} in {Class} cannot override {method} in {Class}; attempting to assign weaker access privileges, was {type of modifier}class Base {
private void a (){
System.out.println("Base: a");
}
void b(){ // <---------------------default
System.out.println("Base: b");
}
void c(){
System.out.println("Base: c");
}
public void ab(){
this.a();
this.b();
}
}
class Derived extends Base{
private void a (){
System.out.println("Derived: a");
}
// this will do override
private void b(){ // <-------private not allow, which narrow the accessibility
// but public > protected > default is allowed.
System.out.println("Derived: b");
}
// this is overload
private void c(int x){ // <-----------private is allow here
System.out.println("Derived: c - overload");
}
}Conclusion:
-
When overriding is perform, we cannot narrow the accessibility, but we can use the same level accessibility or extend it.
-
When overloading is perform, we can narrow the accessibility.
It will static bind to the super class private method, this the tricky point of private access modifier.
Can we override private method in Java? - Example program
No, We can not override private method in Java, just like we can not override static method in Java. Like static methods, private method in Java is also bonded during compile time using static binding by Type information and doesn't depends on what kind of object a particular reference variable is holding. Since method overriding works on dynamic binding, its not possible to override private method in Java. private methods are not even visible to Child class, they are only visible and accessible in the class on which they are declared. private keyword provides highest level of Encapsulation in Java. Though you can hide private method in Java by declaring another private method with same name and different method signature.
Read more: https://www.java67.com/2012/08/can-we-override-private-method-in-java.html#ixzz6JYyFzsC8
Example code here:
class Base {
private void a (){ // <--- this is private method
System.out.println("Base: a");
}
void b(){
System.out.println("Base: b");
}
public void ab(){
this.a();
this.b();
}
}
class Derived extends Base{
private void a (){ // <--- this is private method
System.out.println("Derived: a");
}
void b(){
System.out.println("Derived: b");
}
}
public class playground {
public static void main(String[] args) {
System.out.println("welcome to playground.");
new Derived().ab();
// output:
// Base: a
// Derived: b
}
}Reference:
https://www.java67.com/2012/08/can-we-override-private-method-in-java.html
WIP...