static关键字:用于修饰成员(成员变量和成员函数)
被static修饰后的成员具有以下特点:
随着类的加载而加载,随着类的消亡而消失。生命周期最长。
优先于对象存在
被所有对象所共享
可以直接被类名调用:类名.静态成员
使用时要注意:
静态方法只能访问静态成员
非静态方法既可以访问静态又可以访问非静态。
静态方法中不可以写this、super关键字
因为静态优先于对象存在,所以静态方法不可以出现this。
主函数是静态的
静态的利弊:
好处:节约资源,可以直接被类名调用。
弊端:生命周期长,访问出现局限性。
public class StaticDemo {
public static void main(String[] args) {
Person p = new Person();
p.name = "zhangsan";
p.show();
System.out.println(Person.country);//类名调用
//System.out.println(p.country);//类名调用
}
}
class Person{
String name;//成员变量。实例变量,随对象存在。
static String country = "CN";//静态的成员变量,类变量,
public void show(){
System.out.println(name+"**********"+country);
}
}
主函数:main
public:代表该函数访问权限是最大的。
static :主函数随着类的加载已经存在。
void :主函数没有具体返回值。
main :特殊单词,被JVM识别。
(String[] args):函数的参数,参数类型是个数组,该数组中的元素是字符串,字符数组。
什么时候使用静态:因为静态修饰成员和函数。所以应该从静态变量和静态函数入手
那么什么时候定义静态变量呢?
当对象中出现共享数据时,该数据被静态所修饰(注意区分属性和数据:数据是属性的值,
例如 属性name,它的数据值是zhangsan,lisi等)
什么时候定义静态函数呢?
当功能内部没有访问到非静态数据时(对象特有数据),那么该功能可以定义成静态。
静态代码块:
格式
static
{
静态代码块中的执行语句。
}
特点:随着类的加载而执行,而且只执行一次,
作用:用于给类进行初始化。
代码演示:
package basicTest;
/*
* 这个例子很好的演示了静态代码块 构造代码块 构造函数在程序运行时的加载次序
*
* 静态代码块在初始化对象是就执行而且只执行一次,
* 如果静态代码块与主函数在一个大括号内,则先加载静态代码块
*
* 此外,我们也可以看到,构造代码块的执行优先于构造方法
* */
class Code{
//静态代码块
static{
System.out.println("Code的静态代码块");
}
//构造方法
public Code(){
System.out.println("Code的构造方法");
}
//构造代码块
{
System.out.println("Code的构造块");
}
}
public class CodeBlock03{
{
System.out.println("CodeBlock03的构造块");
}
static{
System.out.println("CodeBlock03的静态代码块");
}
public CodeBlock03(){
System.out.println("CodeBlock03的构造方法");
}
public static void main(String[] args){
System.out.println("CodeBlock03的主方法");
new Code();
/*new Code();
new CodeBlock03();
new CodeBlock03();*/
}
}
单例设计模式:解决一个类在内存中只有一个对象。
* 单例设计模式的代码体现
* 1.私有化构造函数
* 2.创建私有并静态的本类对象(构造函数实例化)
* 3.定义共有并静态方法,返回该类对象
*
* 单例设计模式包括饿汉式和懒汉式
* 先写饿汉式:先初始化对象
package DesignPattern;
class single {
//一进入类就初始化对象,此称为饿汉式
private Single(){}//私有化构造函数
//创建私有并静态的本类对象
private static Single s=new Single{};
//定义共有并静态方法,返回该对象
public static Sinlge getInstance(){
return s;
}
/*
* 懒汉式单例设计模式:被调用时才初始化。
* 也叫延迟加载。
* */
private static Single s=null;
private Single(){};
public static Single getInstance(){
if(s == null)
s=new Single();
return s;
}
}
多线程中的单例
懒汉式 多线程访问时出现安全问题 采用同步函数效率低下(加的锁是该类所属的字节码文件对象 类名.class)
代码实例:
class Single
{
private static Single s=null;
private Single(){}
public static Single getInstance()
{
if(s==null)//减少判断锁的次数,双重判断
{
synchronized(Single.class)//锁是该类所属的字节码文件对象。
{
if(s==null)
s=new Single();
return s;
}
}
}
}
import java.lang.reflect.Method;
/*
编写一个类,增加一个实例方法用于打印一条字符串。
并使用反射手段创建该类的对象, 并调用该对象中的方法。
*/
public class ReflectTest {
public static void main(String[] args) throws Exception {
Class<myClass>clazz = myClass.class;
Method method = clazz.getMethod("printStr", String.class);
method.invoke(clazz.newInstance(),"ni hao hei ma");
}
}
class myClass{
public void printStr(String str){
System.out.println(str);
}
}
/*******************************************************************/
import java.util.*;
public class ArrayListTest {
/*遍历ArrayList中存放的字符串,并删除“abc”*/
public static void main(String[] args) {
ArrayList<String> alist = new ArrayList<String>();
alist.add("hello");
alist.add("java");
alist.add("abc");
alist.add("abe");
alist.add("bcd");
System.out.println(alist.toString());
Iterator<String> it = alist.iterator();
while(it.hasNext())
{
if("abc".equals(it.next()))
it.remove();
}
System.out.println(alist);
}
}
/***********************************************************************/
import java.lang.reflect.Method;
import java.util.*;
public class StringToArrayListTest {
/*在泛型为Integer的ArrayList中存放一个String类型的对象*/
public static void main(String[] args) throws Exception{
ArrayList<Integer> list = new ArrayList<Integer>();
Method method = list.getClass().getMethod("add", Object.class);
method.invoke(list, "hello java");
System.out.println(list.toString());
}
}
/************************************************************************************/
import java.io.*;
import java.util.Scanner;
public class ioTest001 {
/*小程序:实现键盘录入一个字符串,经过翻转后输出*/
public static void main(String[] args) throws IOException {
/*对键盘录入的字符串进行反转后输出
BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));
String str = null;
str = bufr.readLine();
reverseStr(str);
}
private static String reverse(String str) {
String result = "";
char[] ch = str.toCharArray();
for(int i = ch.length-1;i>=0;i--)
{
result += ch[i];
}
return result;
}
private static void reverseStr(String str) {
for(int i = str.length()-1;i>=0;i--){
System.out.print(str.charAt(i));
}*/
/*使用scanner类获取键盘录入*/
Scanner sc = new Scanner(System.in);
System.out.println("请输入姓名: ");
String name = sc.nextLine();
System.out.println("请输入年龄:");
int age = sc.nextInt();
System.out.println("请输入工资: ");
float salary = sc.nextFloat();
System.out.println("您的基本信息如下: ");
System.out.println("姓名:"+name+"\n"+"年龄 :"+age+"\n"+"工资: "+salary+"\n");
}
}
/*******************************************************************************/
方法一:从控制台接收一个字符,然后将其打印出来
import java.io.*;
public static void main(String [] args) throws IOException{
System.out.print("Enter a Char:");
char i = (char) System.in.read();
System.out.println("your char is :"+i);
}
IO之读取本地一个文本文档
import java.io.*;
public class IOTest {
public static void main(String[] args) {
FileInputStream fis = null;
try {
fis = new FileInputStream("d:\\execrise.txt");
byte[] buf = new byte[5];
int len = 0;
while((len = fis.read(buf))!=-1)
{
for(int x = 0;x<len;x++)
{
System.out.print((char)buf[x]);
}
}
} catch (Exception e) {
// TODO: handle exception
throw new RuntimeException("读取失败");
}
finally
{
if(fis != null)
try {
fis.close();
} catch (Exception e2) {
// TODO: handle exception
throw new RuntimeException("关闭流失败");
}
}
}
}
GUI实例,制作自己的txt小软件
package demoGUI;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
class MyMenuTest {
public static void main(String[] args) {
new MyMenuTest();
}
/****************************************************************/
private Frame f;
private MenuBar bar;
private Menu fileMenu;
private TextArea ta;
private File file;
private MenuItem openItem,closeItem,saveItem;
private FileDialog openDialog,saveDialog;
MyMenuTest()
{
init();
}
private void init() {
f = new Frame("我爱胖妞儿");
f.setBounds(450,200,450,450);
//f.setLayout(new FlowLayout());
bar = new MenuBar();
ta = new TextArea();
fileMenu = new Menu("文件");
openItem = new MenuItem("打开");
closeItem = new MenuItem("关闭");
saveItem = new MenuItem("保存");
fileMenu.add(openItem);
fileMenu.add(closeItem);
fileMenu.add(saveItem);
bar.add(fileMenu);
f.setMenuBar(bar);
openDialog = new FileDialog(f,"我要打开",FileDialog.LOAD);
saveDialog = new FileDialog(f,"我要保存",FileDialog.SAVE);
f.add(ta);
myEvent();
f.setVisible(true);
}
private void myEvent() {
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
openItem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
openDialog.setVisible(true);
String dirPath = openDialog.getDirectory();
String fileName = openDialog.getFile();
System.out.println(dirPath+"*****"+fileName);
if(dirPath==null || fileName == null)
return ;
ta.setText("");
file = new File(dirPath,fileName);
try {
BufferedReader bufr = new BufferedReader(new FileReader(file));
String line = null;
while((line = bufr.readLine())!=null)
{
ta.append(line+"\r\n");
}
} catch (Exception e2) {
// TODO: handle exception
throw new RuntimeException("读取失败");
}
}
});
saveItem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
if(file == null)
{
saveDialog.setVisible(true);
String dirPath = saveDialog.getDirectory();
String fileName = saveDialog.getFile();
if(fileName == null || dirPath == null)
return ;
file = new File(dirPath,fileName);
}
try {
BufferedWriter bufw = new BufferedWriter(new FileWriter(file));
String text = ta.getText();
bufw.write(text);
bufw.close();
} catch (Exception e2) {
// TODO: handle exception
throw new RuntimeException("保存失败");
}
}
});
closeItem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
}
}
/*********************************************************************/
/* @author Administrator
*创建新执行线程有两种方法。一种方法是将类声明为 Thread 的子类。
* 该子类应重写 Thread 类的 run 方法。
*另一种方法是声明实现 Runnable 接口的类。该类然后实现 run 方法。
*将实现了Runnable接口的子类对象作为实际参数传递给Thread类中的构造函数。*/
public class ThreadBandTest {
public static void main(String[] args) {
//第1种继承Thread,并复写run方法。
Demo d1 = new Demo();
Demo d2 = new Demo();
d1.run();
d2.run();
//第2种实现Runnable接口。
Cus c = new Cus();
Thread t1 = new Thread(c);
Thread t2= new Thread(c);
t1.start();
t2.start();
}
}
/* 同步的两种表达方式
1,同步代码块
2,同步函数 */
//创建银行类
class Bank{
//储户存入总和
private int sum;
//同步函数,为两个储户线程共享的代码(数据)
/*public synchronized void add(int n){
sum=sum+n;
try {
Thread.sleep(100);
} catch (Exception e) {
// TODO: handle exception
}
System.out.println("sum= "+sum);
}*/
//同步代码块实现线程的代码共享
Object obj = new Object();
public void add(int n){
synchronized (obj) {
sum = sum+n;
try {
Thread.sleep(500);
} catch (Exception e) {
// TODO: handle exception
}
System.out.println("sum = "+sum);
}
}
}
//继承Thread
class Demo extends Thread{
public void run(){
for(int i=0;i<8000;i++)
System.out.println(i);
}
}
//创建储户类 实现Runnable接口
class Cus implements Runnable{
private Bank b = new Bank();
//实现每个储户存储三次,每次100
public void run(){
for(int x=0;x<3;x++){
b.add(100);
}
}
}
/****************************************************************************/
@SuppressWarnings("null")
private static void IPSort() {
FileWriter fos = null;
try {
fos = new FileWriter("d:\\ip.txt");
String ip = "61.54.231.245 61.54.231.9 61.54.231.246 61.54.231.48 61.53.231.249";
ip = ip.replaceAll("(\\d+)","00$1");
ip = ip.replaceAll("0*(\\d{3})","$1");
String[] arr = ip.split(" ");
TreeSet<String>ts = new TreeSet<String>();
for(String s : arr)
{
ts.add(s);
}
for(String s : ts)
{
s = s.replaceAll("0*(\\d)","$1");
fos.write(s+"\r\n");
fos.flush();
System.out.println(s);
}
}
catch (IOException e)
{
throw new RuntimeException("写入失败");
}
finally
{
try
{
if( fos == null)
fos.close();
} catch (Exception e2)
{
throw new RuntimeException("关闭流失败");
}
}
}
/********************************************************************/
import java.awt.Color;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
/**
* Java程序通过字节流和字符流的方式来读取文件数据。
* FileInputStream和FileReader的关键区别在于:FileReader用于读取字符流,而FileInputStream用来读取原始字节流。
* @author Javin Paul
*/
public class HowToReadFileInJava {
public static void main(String args[]) {
// 例1 – 使用FileInputStream 读取文件内容
try (FileInputStream fis = new FileInputStream("data.txt")) {
int data = fis.read();
while (data != -1) {
System.out.print(Integer.toHexString(data));
data = fis.read();
}
} catch (IOException e) {
System.out.println("Failed to read binary data from File");
e.printStackTrace();
}
// 例2 – Java中使用FileReader 读取文件数据
try (FileReader reader = new FileReader("data.txt")) {
int character = reader.read();
while (character != -1) {
System.out.print((char) character);
character = reader.read();
}
} catch (IOException io) {
System.out.println("Failed to read character data from File");
io.printStackTrace();
}
}
}
/*******************************************************************************************************/
越努力越幸运!