文章目錄
全部源碼:https://github.com/name365/JavaSE-30Day
轉載自atguigu.com視頻
第四章 面向對象(下)
關鍵字:static
static 的使用
當我們編寫一個類時,其實就是在描述其對象的屬性和行爲,而並沒有產生實質上的對象,只有通過 new 關鍵字纔會產生出對象,這時系統纔會分配內存空間給對象,其方法纔可以供外部調用。我們有時候希望無論是否產生了對象或無論產生了多少對象的情況下,
某些特定的數據在內存空間裏只有一份
,例如所有的中國人都有個國家名稱,每一箇中國人都共享這個國家名稱,不必在每一箇中國人的實例對象中都單獨分配一個用於代表國家名稱的變量。
/*
* static 關鍵字的使用
*
* 1.static:靜態的。
* 2.static 可以用來修飾:屬性、方法、代碼塊、內部類。
*
* 3.使用 static 修飾屬性:靜態變量(或類變量)。
* 3.1 屬性:是否使用 static 修飾,又分爲:靜態屬性 VS 非靜態屬性(實例變量)
* 實例變量:我們創建了類的多個對象,每個對象都獨立的擁有了一套類中的非靜態屬性。
* 當修改其中一個非靜態屬性時,不會導致其他對象中同樣的屬性值的修飾。
* 靜態變量:我們創建了類的多個對象,多個對象共享同一個靜態變量。當通過靜態變量去修改某一個變量時,
* 會導致其他對象調用此靜態變量時,是修改過的。
* 3.2 static 修飾屬性的其他說明:
* ① 靜態變量隨着類的加載而加載。可以通過"類.靜態變量"的方式進行調用。
* ② 靜態變量的加載要早於對象的創建。
* ③ 由於類只會加載一次,則靜態變量在內存中也只會存在一次。存在方法區的靜態域中。
*
* ④ 類變量 實例變量
* 類 yes no
* 對象 yes yes
*
* 3.3 靜態屬性舉例:System.out.Math.PI;
*
*/
public class StaticTest {
public static void main(String[] args) {
Chinese.nation = "中國";
Chinese c1 = new Chinese();
c1.name = "姚明";
c1.age = 40;
c1.nation = "CHN";
Chinese c2 = new Chinese();
c2.name = "馬龍";
c2.age = 30;
c2.nation = "CHINA";
System.out.println(c1.nation);
//編譯不通過
// Chinese.name = "張繼科";
}
}
//中國人
class Chinese{
String name;
int age;
static String nation;
}
類變量 vs 實例變量內存解析
static 修飾方法
/*
* 4.使用 static 修飾方法:靜態方法
* ① 隨着類的加載而加載,可以通過"類.靜態方法"的方式調用
* ② 靜態方法 非靜態方法
* 類 yes no
* 對象 yes yes
* ③ 靜態方法中,只能調用靜態的方法或屬性
* 非靜態的方法中,可以調用所有的方法或屬性
*
* 5.static 注意點:
* 5.1 在靜態的方法內,不能使用 this 關鍵字、super 關鍵字
* 5.2 關於靜態屬性和靜態方法的使用,大家從生命週期的角度去理解。
*
* 6.開發中,如何確定一個屬性是否需要聲明 static 的?
* 》 屬性是可以被多個對象所共享的,不會隨着對象的不同而不同的。
* 》 類中的常量也常常聲明爲 static
*
* 開發中,如何確定一個方法是否要聲明爲 static 的?
* 》 操作靜態屬性的方法,通常設置爲 static 的
* 》 工具類中的方法,習慣上聲明爲 static 的。比如:Math、Arrays、Collections
*
*/
public class StaticTest {
public static void main(String[] args) {
Chinese.nation = "中國";
Chinese c1 = new Chinese();
//編譯不通過
// Chinese.name = "張繼科";
c1.eat();
Chinese.show();
//編譯不通過
// chinese.eat();
// Chinese.info();
}
}
//中國人
class Chinese{
String name;
int age;
static String nation;
public void eat(){
System.out.println("中國人喫中餐");
//調用非靜態結構
this.info();
System.out.println("name : " + name);
//調用靜態結構
walk();
System.out.println("nation : " + Chinese.nation);
}
public static void show(){
System.out.println("我是一箇中國人!");
// eat();
// name = "Tom";
//可以調用靜態的結構
System.out.println(Chinese.nation);
walk();
}
public void info(){
System.out.println("name : " + name + ",age : " + age);
}
public static void walk(){
}
}
自定義 ArrayUtil 的優化
/*
* 自定義數組工具類
*/
public class ArrayUtil {
// 求數組的最大值
public static int getMax(int[] arr) {
int maxValue = arr[0];
for (int i = 1; i < arr.length; i++) {
if (maxValue < arr[i]) {
maxValue = arr[i];
}
}
return maxValue;
}
// 求數組的最小值
public static int getMin(int[] arr) {
int minValue = arr[0];
for (int i = 1; i < arr.length; i++) {
if (minValue > arr[i]) {
minValue = arr[i];
}
}
return minValue;
}
// 求數組總和
public static int getSum(int[] arr) {
int sum = 0;
for (int i = 0; i < arr.length; i++) {
sum += arr[i];
}
return sum;
}
// 求數組平均值
public static int getAvg(int[] arr) {
int avgValue = getSum(arr) / arr.length;
return avgValue;
}
//如下兩個同名方法構成重載
// 反轉數組
public static void reverse(int[] arr) {
for (int i = 0; i < arr.length / 2; i++) {
int temp = arr[i];
arr[i] = arr[arr.length - i - 1];
arr[arr.length - i - 1] = temp;
}
}
public void reverse(String[] arr){
}
// 複製數組
public static int[] copy(int[] arr) {
int[] arr1 = new int[arr.length];
for (int i = 0; i < arr1.length; i++) {
arr1[i] = arr[i];
}
return null;
}
// 數組排序
public static void sort(int[] arr) {
for (int i = 0; i < arr.length - 1; i++) {
for (int j = 0; j < arr.length - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
// int temp = arr[j];
// arr[j] = arr[j + 1];
// arr[j + 1] = temp;
//錯誤的:
// swap(arr[j],arr[j+1]);
swap(arr,j ,j+1);
}
}
}
}
//錯誤的:交換數組中兩個指定位置元素的值
// public void swap(int i,int j){
// int temp = i;
// i = j;
// j = temp;
// }
//正確的:
private static void swap(int[] arr,int i,int j){
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
// 遍歷數組
public static void print(int[] arr) {
System.out.print("[");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + ",");
}
System.out.println("]");
}
// 查找指定元素
public static int getIndex(int[] arr, int dest) {
//線性查找
for (int i = 0; i < arr.length; i++) {
if (dest==arr[i]) {
return i;
}
}
return -1;
}
}
- 測試類
public class ArrayUtilTest {
public static void main(String[] args) {
// ArrayUtil util = new ArrayUtil();
int[] arr = new int[]{32,5,26,74,0,96,14,-98,25};
int max = ArrayUtil.getMax(arr);
System.out.println("最大值爲:" + max);
System.out.print("排序前:");
ArrayUtil.print(arr);
ArrayUtil.sort(arr);
System.out.print("排序後:");
ArrayUtil.print(arr);
// System.out.println("查找:");
// int index = util.getIndex(arr, 5);
// if(index > 0){
// System.out.println("找到了,索引地址:" + index);
// }else{
// System.out.println("沒找到");
// }
}
}
static 的應用舉例
//static 關鍵字的應用
public class CircleTest {
public static void main(String[] args) {
Circle c1 = new Circle();
Circle c2 = new Circle();
Circle c3 = new Circle();
System.out.println("c1 的 ID:" + c1.getId());
System.out.println("c2 的 ID:" + c2.getId());
System.out.println("c3 的 ID:" + c3.getId());
System.out.println("創建圓的個數: " + Circle.getTotal());
}
}
class Circle{
private double radius;
private int id; //需要自動賦值
public Circle(){
id = init++;
total++;
}
public Circle(double radius){
this();
//或
// id = init++;
// total++;
this.radius = radius;
}
private static int total;//記錄創建圓的個數
private static int init = 1001;//static 聲明的屬性被所有對象所共享
public double findArea(){
return 3.14 * radius * radius;
}
public double getRadius() {
return radius;
}
public void setRadius(double radius) {
this.radius = radius;
}
public int getId() {
return id;
}
public static int getTotal() {
return total;
}
}
static 的練習
/*
* 編寫一個類實現銀行賬戶的概念,包含的屬性有“帳號”、“密碼”、“存款餘額”、
* “利率”、“最小余額”,定義封裝這些屬性的方法。
* 賬號要自動生成。編寫主類,使用銀行賬戶類,輸入、輸出 3 個儲戶的上述信息。
* 考慮:哪些屬性可以設計成 static 屬性。
*
*/
public class Account {
private int id; //賬號
private String pwd = "000000"; //密碼
private double balance; //存款餘額
private static double interestRate; //利率
private static double minMoney = 1.0; //最小余額
private static int init = 1001; //用於自動生成 id
public Account(){ //賬號自動生成
id = init++;
}
public Account(String pwd,double balance){
id = init++;
this.pwd = pwd;
this.balance = balance;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public static double getInterestRate() {
return interestRate;
}
public static void setInterestRate(double interestRate) {
Account.interestRate = interestRate;
}
public static double getMinMoney() {
return minMoney;
}
public static void setMinMoney(double minMoney) {
Account.minMoney = minMoney;
}
public int getId() {
return id;
}
public double getBalance() {
return balance;
}
@Override
public String toString() {
return "Account [id=" + id + ", pwd=" + pwd + ", balance=" + balance + "]";
}
}
- 測試類
public class AccountTest {
public static void main(String[] args) {
Account acct1 = new Account();
Account acct2 = new Account("qwerty",2000);
Account.setInterestRate(0.012);
Account.setMinMoney(100);
System.out.println(acct1);
System.out.println(acct2);
System.out.println(acct1.getInterestRate());
System.out.println(acct1.getMinMoney());
}
}
單例(Singleton)設計模式
設計模式是
在大量的實踐中總結和理論化之後優選的代碼結構、編程風格、以及解決問題的思考方式
。設計模免去我們自己再思考和摸索。就像是經典的棋譜,不同的棋局,我們用不同的棋譜。”套路”
-
所謂類的單例設計模式,就是採取一定的方法保證在整個的軟件系統中,對某個類
只能存在一個對象實例
,並且該類只提供一個取得其對象實例的方法。如果我們要讓類在一個虛擬機中只能產生一個對象,我們首先必須將類的構造器的訪問權限設置爲 private
,這樣,就不能用 new 操作符在類的外部產生類的對象了,但在類內部仍可以產生該類的對象。因爲在類的外部開始還無法得到類的對象,只能調用該類的某個靜態方法以返回類內部創建的對象
,靜態方法只能訪問類中的靜態成員變量,所以,指向類內部產生的該類對象的變量也必須定義成靜態的
。 -
詳細瞭解,可以參閱《大話設計模式》
-
有關設計模式的兩個簡化概述版本:
-
單例模式的餓漢式
/*
* 單例設計模式:
* 1.所謂類的單例設計模式,就是採取一定的方法保證在整個的軟件系統中,對某個類只能存在一個對象實例
*
* 2.如何實現?
* 餓漢式 VS 懶漢式
*
* 3.區分餓漢式和懶漢式。
* 餓漢式:壞處:對象加載時間過長。
* 好處:餓漢式是線程安全的。
*
* 懶漢式:好處:延遲對象的創建。
* 壞處:目前的寫法,會線程不安全。---》到多線程內容時,再修改
*/
public class SingletonTest {
public static void main(String[] args) {
// Bank bank1 = new Bank();
// Bank bank2 = new Bank();
Bank bank1 = Bank.getInstance();
Bank bank2 = Bank.getInstance();
System.out.println(bank1 == bank2);
}
}
//單例的餓漢式
class Bank{
//1.私有化類的構造器
private Bank(){
}
//2.內部創見類的對象
//4.要求此對象也必須聲明爲靜態的
private static Bank instance = new Bank();
//3.提供公共的靜態的方法,返回類的對象。
public static Bank getInstance(){
return instance;
}
}
- 單例模式的懶漢式
/*
* 單例的懶漢式實現
*
*/
public class SingletonTest2 {
public static void main(String[] args) {
Order order1 = Order.getInstance();
Order order2 = Order.getInstance();
System.out.println(order1 == order2);
}
}
class Order{
//1.私有化類的構造器
private Order(){
}
//2.聲明當前類對象,沒有初始化。
//此對象也必須聲明爲 static 的
private static Order instance = null;
//3.聲明 public、static 的返回當前類對象的方法
public static Order getInstance(){
if(instance == null){
instance = new Order();
}
return instance;
}
}
- 單例模式的優點
由於單例模式只生成一個實例,
減少了系統性能開銷
,當一個對象的產生需要比較多的資源時,如讀取配置、產生其他依賴對象時,則可以通過在應用啓動時直接產生一個單例對象,然後永久駐留內存的方式來解決。
- 單例(Singleton)設計模式-應用場景
網站的計數器
,一般也是單例模式實現,否則難以同步。應用程序的日誌應用
,一般都使用單例模式實現,這一般是由於共享的日誌文件一直處於打開狀態,因爲只能有一個實例去操作,否則內容不好追加。數據庫連接池
的設計一般也是採用單例模式,因爲數據庫連接是一種數據庫資源。- 項目中,
讀取配置文件的類
,一般也只有一個對象。沒有必要每次使用配置文件數據,都生成一個對象去讀取。 Application
也是單例的典型應用- Windows 的
Task Manager (任務管理器
)就是很典型的單例模式 - Windows 的
Recycle Bin(回收站)
也是典型的單例應用。在整個系統運行過程中,回收站一直維護着僅有的一個實例。
理解 main 方法的語法(瞭解)
由於 Java 虛擬機需要調用類的 main()方法,所以該方法的訪問權限必須是 public,又因爲 Java 虛擬機在執行 main()方法時不必創建對象,所以該方法必須是 static 的,該方法接收一個 String 類型的數組參數,該數組中保存執行 Java 命令時傳遞給所運行的類的參數。
又因爲 main() 方法是靜態的,我們不能直接訪問該類中的非靜態成員,必須創建該類的一個實例對象後,才能通過這個對象去訪問類中的非靜態成員,這種情況,我們在之前的例子中多次碰到。
/*
* main()方法的使用說明
* 1.main()方法作爲程序的入口;
* 2.main()方法也是一個普通的靜態方法
* 3.main()方法也可以作爲我們與控制檯交互的方式。(之前,使用 Scanner)
*
*
*/
public class MainTest {
public static void main(String[] args) { //入口
Main.main(new String[100]);
MainTest test = new MainTest();
test.show();
}
public void show(){
}
}
class Main{
public static void main(String[] args) {
args = new String[100];
for(int i = 0;i < args.length;i++){
args[i] = "args_" + i;
System.out.println(args[i]);
}
}
}
- 命令行參數用法舉例
public class MainDemo {
public static void main(String[] args) {
for(int i = 0;i < args.length;i++){
System.out.println("/*/*/*/"+ args[i]);
}
}
}
//運行程序 MainDemo.java
javac MainDemo.java
java MainDemo “Tom” “Jerry” “Shkstart”
類的成員之四:代碼塊
/*
* 類的成員之四:代碼塊(或初始化塊)
*
* 1.代碼塊的作用:用來初始化類、對象的
* 2.代碼塊如果有修飾的話,只能使用 static
* 3.分類:靜態代碼塊 vs 非靜態代碼塊
*
* 4.靜態代碼塊
* 》內部可以有輸出語句
* 》隨着類的加載而執行,而且只執行一次
* 》作用:初始化類的信息
* 》如果一個類中,定義了多個靜態代碼塊,則按照聲明的先後順序執行
* 》靜態代碼塊的執行,優先於非靜態代碼塊的執行
* 》靜態代碼塊內只能調用靜態的屬性、靜態的方法,不能調用非靜態的結構
*
* 5.非靜態代碼塊
* >內部可以有輸出語句
* >隨着對象的創建而執行
* >每創建一個對象,就執行一次非靜態代碼塊。
* >作用:可以在創建對象時,對對象的屬性等進行初始化。
* >如果一個類中,定義了多個非靜態代碼塊,則按照聲明的先後順序執行
* >非靜態代碼塊內可以調用靜態的屬性、靜態的方法,或非靜態的屬性、非靜態的方法。
*
* 對屬性可以賦值的位置:
* ①默認初始化
* ②顯式初始化
* ③構造器中初始化
* ④有了對象以後,可以通過"對象.屬性"或"對象.方法"的方式,進行賦值。
* ⑤在代碼塊中賦值
*/
public class BlockTest {
public static void main(String[] args) {
String desc = Person.desc;
System.out.println(desc);
Person p1 = new Person();
Person p2 = new Person();
System.out.println(p1.age);
Person.info();
}
}
class Person{
//屬性
String name;
int age;
static String desc = "我是一個青年";
//構造器
public Person(){
}
//static 的代碼塊
static{
System.out.println("hello,static block-1");
//調用靜態結構
desc = "我是一個愛小說的人";
info();
//不能調用非靜態結構
// eat();
// name = "Tom";
}
static{
System.out.println("hello,static block-2");
}
//非 static 的代碼塊
{
System.out.println("hello,block-2");
}
{
System.out.println("hello,block-1");
//調用非靜態結構
age = 1;
eat();
//調用靜態結構
desc = "我是一個愛小說的人 1";
info();
}
//方法
public Person(String name,int age){
this.name = name;
this.age = age;
}
public void eat(){
System.out.println("喫飯");
}
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + "]";
}
public static void info(){
System.out.println("我是一個快樂的人。");
}
}
- 靜態初始化塊舉例 1
//總結:由父類到子類,靜態先行
class Root{
static{
System.out.println("Root 的靜態初始化塊");
}
{
System.out.println("Root 的普通初始化塊");
}
public Root(){
System.out.println("Root 的無參數的構造器");
}
}
class Mid extends Root{
static{
System.out.println("Mid 的靜態初始化塊");
}
{
System.out.println("Mid 的普通初始化塊");
}
public Mid(){
System.out.println("Mid 的無參數的構造器");
}
public Mid(String msg){
//通過 this 調用同一類中重載的構造器
this();
System.out.println("Mid 的帶參數構造器,其參數值:"
+ msg);
}
}
class Leaf extends Mid{
static{
System.out.println("Leaf 的靜態初始化塊");
}
{
System.out.println("Leaf 的普通初始化塊");
}
public Leaf(){
//通過 super 調用父類中有一個字符串參數的構造器
super("尚硅谷");
System.out.println("Leaf 的構造器");
}
}
public class LeafTest{
public static void main(String[] args){
new Leaf();
//new Leaf();
}
}
- 靜態初始化塊舉例 2
class Father {
static {
System.out.println("11111111111");
}
{
System.out.println("22222222222");
}
public Father() {
System.out.println("33333333333");
}
}
public class Son extends Father {
static {
System.out.println("44444444444");
}
{
System.out.println("55555555555");
}
public Son() {
System.out.println("66666666666");
}
public static void main(String[] args) { // 由父及子 靜態先行
System.out.println("77777777777");
System.out.println("************************");
new Son();
System.out.println("************************");
new Son();
System.out.println("************************");
new Father();
}
}
- 總結:程序中成員變量賦值的執行順序
/*
* 對屬性可以賦值的位置:
* ①默認初始化
* ②顯式初始化 / ⑤在代碼塊中賦值
* ③構造器中初始化
* ④有了對象以後,可以通過"對象.屬性"或"對象.方法"的方式,進行賦值。
*
* 執行的先後順序:① - ② / ⑤ - ③ - ④
*/
public class OrderTest {
public static void main(String[] args) {
Order order = new Order();
System.out.println(order.orderId);
}
}
class Order{
int orderId = 3;
{
orderId = 4;
}
}
關鍵字:final
/*
* final:最終的
*
* 1.final可以用來修飾的結構:類、方法、變量
*
* 2.final用來修飾一個類:此類不能被其他類所繼承。
* 比如:String類、System類、StringBuffer類
* 3.final修飾一個方法:final標記的方法不能被子類重寫。
* 比如:Object類中的getClass()。
* 4.final用來修飾變量:此時的"變量"(成員變量或局部變量)就是一個常量。名稱大寫,且只能被賦值一次。
* 4.1 final修飾屬性,可以考慮賦值的位置有:顯式初始化、代碼塊中初始化、構造器中初始化
* 4.2 final修飾局部變量:
* 尤其是使用final修飾形參時,表明此形參是一個常量。當我們調用此方法時,給常量形參賦一個實參。
* 一旦賦值以後,就只能在方法體內使用此形參,但不能進行重新賦值。
*
* static final 用來修飾:全局常量
*/
public class FinalTest {
final int WIDTH = 0;
final int LEFT;
final int RIGHT;
// final int DOWN;
{
LEFT = 1;
}
public FinalTest(){
RIGHT = 2;
}
public FinalTest(int n){
RIGHT = n;
}
// public void setDown(int down){
// this.DOWN = down;
// }
public void dowidth(){
// width = 20; //width cannot be resolved to a variable
}
public void show(){
final int NUM = 10; //常量
// num += 20;
}
public void show(final int num){
System.out.println(num);
}
public static void main(String[] args) {
int num = 10;
num = num + 5;
FinalTest test = new FinalTest();
// test.setDown(5);
test.show(10);
}
}
final class FianlA{
}
//class B extends FinalA{ //錯誤,不能被繼承。
//
//}
//class C extends String{
//
//}
class AA{
public final void show(){
}
}
//class BB extends AA{ // 錯誤,不能被重寫。
// public void show(){
//
// }
//}
- 面試題1
public class Something {
public int addOne(final int x) {
return ++x; // return x + 1;
}
}
- 面試題2
public class Something {
public static void main(String[] args) {
Other o = new Other();
new Something().addOne(o);
}
public void addOne(final Other o) {
// o = new Other();
o.i++;
}
}
class Other {
public int i;
}
整個Java全棧系列都是筆者自己敲的筆記。寫作不易,如果可以,點個讚唄!✌