快捷键的使用
说明
public static void main(String[] args)
一、JAVA语言概述
图形化界面操作与命令行操作
常用命令行指令
计算机语言划分
JAVA语言历史及技术体系平台
java语言的特点
JVM跨平台与垃圾收集机制
JAVA语言环境搭建、下载安装
安装完后配置环境变量path
第一个java程序HelloWorld
单行、多行注释
文档注释
API文档说明
开发工具
小测试
二、java基本语法
1.关键字和保留字
2. 标识符命名规则与规范
3.变量
4.进制
计算机底层都以补码的方式存储数据!
小测试
5.运算符
算数运算符
赋值运算符
比较运算符
逻辑运算符
位运算符
三元运算符
运算符的优先级
6.流程控制
if-else结构
小测试
Scanner从键盘获取数据
switch—case结构
4.
循环结构
eclipse使用
三、数组
一维数组
多维数组
数组中常见算法
Arrays工具类
数组中常见异常
四、方法
方法重载
可变个数的形参
值传递机制
尚硅谷211课
package com.djw;
public class test1 {
public static void main(String[] args) {
test1 test=new test1();
test.first();
}
public class value{
int i=15;
}
public void first(){
int i=5;
value v=new value();
v.i=25;
second(v,i);
System.out.println(v.i);
}
public void second(value v,int i){
i=0;
v.i=20;
value val=new value();
v=val;
System.out.println(v.i+" "+i);//20 0
}
}
package com.djw;
public class test1 {
public static void main(String[] args) {
circle cir= new circle();
passobject pass=new passobject();
pass.printareas(cir,5);
}
}
class circle {
double radius;
public double findArea(){
return Math.PI*radius*radius;
}
}
class passobject{
public void printareas(circle c,int time){
for (int i=0;i<time;i++){
c.radius=i;
System.out.print(i+" ");
System.out.println(c.findArea());
}
}
}
递归方法
五、面向对象
面向过程与面向对象
基本元素:类和对象
类的内部结构1:属性和方法
如何使用类?
类属性和局部变量
类中方法的声明和使用
package packagepractice;
public class lei_duixiang {
public static void main(String[] args) {
//创建类对象
lei p1=new lei();
p1.eat();
System.out.print(p1.age);
System.out.print(p1.getnation("China"));
}
}
class lei{
//属性
String name;
int age=1;
//方法
public void eat() {
System.out.print("吃饭了先生");
}
public String getnation(String nation) {
return nation;
}
}
package packagepractice;
public class lianxi {
public static void main(String[] args) {
person p1=new person();
p1.name="TOM";
p1.age=18;
p1.sex="male";
p1.study();
p1.showage();
System.out.println("addage: "+p1.addage(2));
/*********************************/
person p2=new person();
p2.showage();
System.out.println("addage: "+p2.addage(2));
}
}
class person{
String name;
int age;
String sex;
public void study(){
System.out.println("studying");
}
public void showage(){
System.out.println("age: "+age);
}
public int addage(int i) {
age+=i;
return age;
}
}
package packagepractice;
public class method {
public static void main(String[] args) {
method pi= new method();
//3.1
// pi.wujiaoxing();
//3.2
// System.out.print(pi.wujiaoxing1());
//3.3
System.out.print(pi.wujiaoxing2(10,8));
}
public void wujiaoxing() {
for(int i=0;i<10;i++) {
for(int j=0;j<8;j++) {
System.out.print("*");
}
System.out.println();
}
}
public int wujiaoxing1() {
for(int i=0;i<10;i++) {
for(int j=0;j<8;j++) {
System.out.print("*");
}
System.out.println();
}
return 10*8;
}
public int wujiaoxing2(int m,int n) {
for(int i=0;i<m;i++) {
for(int j=0;j<n;j++) {
System.out.print("*");
}
System.out.println();
}
return m*n;
}
}
package packagepractice;
public class xianxi {
public static void main(String[] args) {
//声明一个Student对象数组
Student[] stus=new Student[20];
for(int i=0;i<20;i++) {
stus[i]=new Student();
//给属性赋值
//学号
stus[i].number=(i+1);
//年级1-6
stus[i].state=(int)(Math.random()*6+1);
//成绩0-100
stus[i].score=(int)(Math.random()*(100));
}
//遍历学生数组
for(int i=0;i<stus.length;i++) {
// System.out.print(stus[i].number+" ");
// System.out.print(stus[i].state+" ");
// System.out.print(stus[i].score+" ");
// System.out.println();
System.out.println(stus[i].info());
}
System.out.println();
//打印三年级学生信息
for(int i=0;i<stus.length;i++) {
if(stus[i].state==3) {
System.out.println(stus[i].info());
}
}
System.out.println();
//冒泡排序,按照学生的成绩遍历学生信息(排序的是对象!!不是成绩)
for(int i=0;i<stus.length-1;i++) {
for(int j=0;j<stus.length-1-i;j++)
if(stus[j].score>stus[j+1].score) {
Student temp=stus[j];
stus[j]=stus[j+1];
stus[j+1]=temp;
}
}
for(int i=0;i<stus.length;i++) {
System.out.println(stus[i].info());
}
}
}
class Student{
int number;
int state;
int score;
public String info() {
return "学号:"+number+" ,年级:"+state+" ,成绩:"+score;
}
}
类的内部结构2:构造器(或构造方法)
package com.djw;
public class PersonTest {
public static void main(String[] args) {
Person P=new Person();
P.setAge(6);
System.out.println(P.getAge());
Person P1=new Person("Ben",21);
System.out.println(P1.getName());
P1.setName("TOM");
System.out.println(P1.getAge()+P1.getName());
}
}
public class Person {
//属性
private int age;
private String name;
//构造器
public Person(){
age=18;
}
public Person(String n,int a){
name=n;
age=a;
}
//方法
public void setAge(int a){
if (a<0||a>130){
System.out.println("输入数据非法");
}else {
age=a;
}
}
public int getAge(){
return age;
}
public void setName(String n){
name =n;
}
public String getName(){
return name;
}
}
package com.djw;
public class TriAngleTest {
public static void main(String[] args) {
TriAngle tri =new TriAngle(5.2,3.77);
tri.setBase(2.1);
tri.setHeight(6.2);
System.out.println(tri.getBase()+" "+tri.getHeight());
}
}
public class TriAngle {
//属性
private double base;
private double height;
//构造器
public TriAngle(){
}
public TriAngle(double b,double h){
base=b;
height=h;
}
//方法
public void setBase(double b){
base= b;
}
public double getBase(){
return base;
}
public void setHeight(double h){
height=h;
}
public double getHeight(){
return height;
}
}
JAVABean
封装性
package com.djw;
public class test1 {
public static void main(String[] args) {
animal an=new animal();
an.setLegs(-6);
an.show();
}
}
class animal{
private int legs;
//对属性设置
public void setLegs(int l){
if (l>=0 && l%2==0){
legs=l;
}else {
legs=0;
}
}
//对属性的获取
public int getLegs(){
return legs;
}
public void show(){
System.out.println(legs);
}
}
package com.djw;
public class PersonTest {
public static void main(String[] args) {
Person P=new Person();
P.setAge(6);
System.out.println(P.getAge());
}
}
public class Person {
private int age;
public void setAge(int a){
if (a<0||a>130){
System.out.println("输入数据非法");
}else {
age=a;
}
}
public int getAge(){
return age;
}
}
this关键字
UML类图
package com.djw;
public class Test {
public static void main(String[] args) {
person p= new person();
p.setAge(15);
System.out.println(p.age);
person p1= new person();
System.out.println(p1.age);
}
}
class person{
String name;
int age;
public void setName(String name){
this.name=name;
}
public void setAge(int age) {
this.age = age;
}
}
//课时233
package com.djw;
package com.djw;
public class BOYGIRLTEST {
public static void main(String[] args) {
BOY boy=new BOY("罗密欧",25);
boy.shout();
GIRL girl=new GIRL("朱丽叶",18);
girl.marry(boy);
System.out.println(girl.getAge());
GIRL girl1=new GIRL("祝英台",19);
int compare=girl.compare(girl1);
if (compare>0){
System.out.println(girl.getName()+"年龄更大");
}else {
System.out.println(girl1.getName()+"年龄更大");
}
}
}
public class BOY {
//属性
private String name;
private int age;
//构造器
public BOY(String name,int age){
this.age=age;
this.name=name;
}
//方法
public void setName(String name){
this.name=name;
}
public String getName(){
return name;
}
public void setAge(int age){
this.age=age;
}
public int getAge(){
return age;
}
public void marry(GIRL girl){
System.out.println(name+"想娶"+girl.getName());
}
public void shout(){
if (age>=22){
System.out.println("你可以合法登记:"+name);
}else {
System.out.println("多谈一谈恋爱");
}
}
}
public class GIRL {
private String name;
private int age;
//构造器
public GIRL(String name,int age){
this.name=name;
this.age=age;
}
//方法
public void setName(String name){
this.name=name;
}
public String getName(){
return name;
}
public void setAge(int age){
this.age=age;
}
public int getAge(){
return age;
}
public void marry(BOY boy){
if (age<boy.getAge()){
System.out.println(name+":我想嫁给你");
boy.marry(this);
}
}
public int compare(GIRL girl){
return this.age-girl.age;
}
}
练习:
package com.djw;
public class BankTTEST {
public static void main(String[] args) {
Bank bank=new Bank();
bank.addCustomer("JANE","SMITH");
bank.getCustomer(0).setAccount(new Account(2000));
bank.getCustomer(0).getAccount().withdraw(500);
double balance=bank.getCustomer(0).getAccount().getBalance();
System.out.println("客户:"+bank.getCustomer(0).getFirstName()
+"余额为"+balance);
bank.addCustomer("万里","杨");
System.out.println(bank.getCustomer(1).getFirstName());
}
}
public class Account {
private double balance;
//创建构造器
public Account(double init_balance){
this.balance=init_balance;
}
public double getBalance(){
return balance;
}
//存钱
public void deposit(double amt){
if (amt>0){
balance+=amt;
System.out.println("存钱成功");
}
}
//取钱
public void withdraw(double amt){
if (balance>=amt){
balance-=amt;
System.out.println("取钱成功");
}else {
System.out.println("余额不足");
}
}
}
public class Customer {
private String firstName;
private String lastName;
private Account account;
//构造器
public Customer(String f,String l){
firstName=f;
lastName=l;
}
public String getFirstName(){
return firstName;
}
public String getLastName(){
return lastName;
}
public void setAccount(Account account){
this.account=account;
}
public Account getAccount(){
return account;
}
}
public class Bank {
private Customer customer[];
private int numberofCustomers;
//构造器
public Bank(){
customer=new Customer[10];
}
//添加用户
public void addCustomer(String f,String l){
Customer cust=new Customer(f,l);
customer[numberofCustomers]=cust;
numberofCustomers++;
}
//用户数量
public int getNumberofCustomers(){
return numberofCustomers;
}
//
public Customer getCustomer(int index){
if (index>=0&&index<numberofCustomers){
return customer[index];
}
return null;
}
}
package关键字
MVC设计模式
import关键字
小项目(增删改查)
package Customer_model;
public class Customer {
//属性
private String name;
private char gender;//性别
private int age;
private String phone;
private String email;
//构造器
public Customer(){
}
public Customer(String name, char gender, int age, String phone, String email) {
this.name = name;
this.gender = gender;
this.age = age;
this.phone = phone;
this.email = email;
}
//get/set方法
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public char getGender() {
return gender;
}
public void setGender(char gender) {
this.gender = gender;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
package Customer_controller;
import Customer_model.Customer;
public class CustomerList {
private Customer customers[];
private int total = 0;
// 在构造器中初始化customers数组
public CustomerList(int totalCustomer) {
customers = new Customer[totalCustomer];//初始化customers数组,记录客户对象个数
}
//客户添加到数组中
public boolean addCustomers(Customer customer){
if (total>=customers.length){
return false;
}else {
customers[total]=customer;
total++;
return true;
}
}
//修改客户信息
public boolean replaceCustomer(int index,Customer customer){
if (index<0||index>=total){
return false;
}else {
customers[index]=customer;
return true;
}
}
//删除客户信息
public boolean deleteCustomer(int index){
if (index<0||index>=total){
return false;
}
for (int i=index;i<total-1;i++){
customers[i]=customers[i+1];
}
//索引最后元素置空
customers[total-1]=null;
total--;
return true;
}
//获取客户信息
public Customer[] getALLCustomers(){
Customer[] custs= new Customer[total];
for (int i=0;i<total;i++){
custs[i]=customers[i];
}
return custs;
}
//获取指定位置客户信息
public Customer getCustomer(int index){
if (index<0||index>=total){
return null;
}
return customers[index];
}
// 获取存储客户的数量
public int getTotal(){
return total;
}
}
package Customer_view;
import Customer_controller.CustomerList;
import Customer_model.Customer;
import util.CMUtility;
public class CustomerView {
CustomerList customerList=new CustomerList(10);
//构造器
public CustomerView(){
Customer customer=new Customer("王陶",'男',23,"1332588515","888446@qq.com");
customerList.addCustomers(customer);
}
//显示客户管理软件界面
public void enterMainmenu() {
boolean flag = true;
while (flag) {
System.out.println("\n-------------客户信息管理软件---------------");
System.out.println(" 1.添加客户");
System.out.println(" 2.修改客户");
System.out.println(" 3.删除客户");
System.out.println(" 4.客户列表");
System.out.println(" 5.退出\n");
System.out.println(" 请选择(1-5):");
char menu = CMUtility.readMenuSelection();
switch (menu) {
case '1':
addNewcustomer();
break;
case '2':
modifyCustomer();
break;
case '3':
deleteCustomer();
break;
case '4':
listallcustomers();
break;
case '5':
System.out.println("确认是否退出(Y/N):");
char exit = CMUtility.readConfirmSelection();
if (exit == 'Y') {
flag = false;
}
}
}
}
//显示客户列表
private void listallcustomers(){
System.out.println("---------客户列表------------");
if (customerList.getTotal()==0){
System.out.println("没有客户信息");
}else {
System.out.println("编号\t姓名\t性别\t年龄\t电话\t邮箱");
Customer custs[]= customerList.getALLCustomers();
for (int i = 0; i < custs.length; i++) {
Customer cust=custs[i];
System.out.println((i+1)+"\t"+cust.getName()+"\t"+cust.getGender()+
"\t"+cust.getAge()+"\t"+cust.getPhone()+"\t"+cust.getEmail());
}
}
System.out.println("---------客户列表完成-----------");
}
//添加客户
private void addNewcustomer(){
System.out.println("-------------添加客户------------");
System.out.println("姓名:");
String name=CMUtility.readString(10) ;
System.out.println("性别:");
char gender=CMUtility.readChar();
System.out.println("年龄:");
int age=CMUtility.readInt();
System.out.println("电话:");
String phone=CMUtility.readString(13);
System.out.println("邮箱:");
String email=CMUtility.readString(30);
//将上述数据封装到对象中
Customer customer=new Customer(name,gender,age,phone,email);
boolean success=customerList.addCustomers(customer);
if (success){
System.out.println("-----------添加完成------------");
}else {
System.out.println("-------客户目录已满添加失败-------");
}
}
//修改客户
private void modifyCustomer() {
System.out.println("------------修改客户-------------");
Customer cust;
int number;
for (; ; ) {
System.out.print("请选择待修改客户编号(-1退出):");
number = CMUtility.readInt();
if (number == -1) {
return;
}
cust = CustomerList.getCustomer(number-1);
if (cust == null) {
System.out.println("无法找到指定客户");
} else {
break;
}
}
//修改客户信息
System.out.println("姓名(" + cust.getName() + "):");
String name = CMUtility.readString(10, cust.getName());
System.out.println("性别(" + cust.getGender() + "):");
char gender = CMUtility.readChar(cust.getGender());
System.out.println("年龄(" + cust.getAge() + "):");
int age = CMUtility.readInt(cust.getAge());
System.out.println("电话(" + cust.getName() + "):");
String phone = CMUtility.readString(13, cust.getPhone());
System.out.println("邮箱(" + cust.getName() + "):");
String email = CMUtility.readString(30, cust.getEmail());
Customer newCust = new Customer(name, gender, age, phone, email);
boolean isreplaced = CustomerList.replaceCustomer(number - 1, newCust);
if (isreplaced) {
System.out.println("---------------修改完成----------------");
} else {
System.out.println("---------------修改失败----------------");
}
}
public void deleteCustomer(){
//删除客户
System.out.println("----------------删除客户---------------");
int number;
for (;;){
System.out.println("请选择删除客户编号(-1退出):");
number=CMUtility.readInt();
if (number==-1){
return;
}
Customer customer=CustomerList.getCustomer(-1);
if (customer==null){
System.out.println("无法找到指定客户");
}else {
break;
}
}
//找到客户后删除
System.out.println("是否确认删除(Y/N):");
char delete=CMUtility.readConfirmSelection();
if (delete=='Y'){
boolean detesucess=CustomerList.deleteCustomer(number-1);
if (detesucess){
System.out.println("删除成功");
}else {
System.out.println("删除失败");
}
}else {
return;
}
}
public static void main(String[] args) {
CustomerView view=new CustomerView();
view.enterMainmenu();
}
}
继承性
package jicheng;
public class Mankind {
private int sex;
private int salary;
public Mankind(){
}
public Mankind(int sex, int salary) {
this.sex = sex;
this.salary = salary;
}
public void manorwoman(){
if (sex==1){
System.out.println("man");
}else if (sex==0){
System.out.println("woman");
}
}
public void employed(){
String info=(salary==0)?"no job":"have job";
System.out.println(info);
}
public int getSex() {
return sex;
}
public void setSex(int sex) {
this.sex = sex;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
}
public class Kids extends Mankind{
private int yearsold;
public void printage(){
System.out.println("年龄为:"+yearsold);
}
//构造器
public Kids(){
}
public Kids(int yearsold) {
this.yearsold = yearsold;
}
public int getYearsold() {
return yearsold;
}
public void setYearsold(int yearsold) {
this.yearsold = yearsold;
}
}
public class Kidstest {
public static void main(String[] args) {
Kids kid=new Kids(12);
kid.printage();
kid.setSalary(2);
System.out.println("薪水为:"+kid.getSalary());
kid.setSex(1);
kid.manorwoman();
kid.employed();
}
}
package jicheng;
public class Circle {
private double radius;
public Circle() {
radius = 1.0;
}
public double getRadius() {
return radius;
}
public void setRadius(double radius) {
this.radius = radius;
}
public double findarea(){
return Math.PI*radius*radius;
}
}
public class Cylinder extends Circle{
private double length;
public Cylinder(){
length=1.0;
}
public double getLength() {
return length;
}
public void setLength(double length) {
this.length = length;
}
public double findvolume(){
return findarea()*getLength();
}
}
public class Cylindertest {
public static void main(String[] args) {
Cylinder cy= new Cylinder();
cy.setLength(3);
cy.setRadius(2);
System.out.println(cy.findvolume());
}
}
方法的重写
super关键字
子类对象实例化过程
package jicheng;
public class Account {
private int id;
private double balance;
private double annualInterestRate;
public Account(int id, double balance, double annualInterestRate) {
this.id = id;
this.balance = balance;
this.annualInterestRate = annualInterestRate;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
public double getAnnualInterestRate() {
return annualInterestRate;
}
public void setAnnualInterestRate(double annualInterestRate) {
this.annualInterestRate = annualInterestRate;
}
//返回月利率
public double getMonthlyinterest(){
return annualInterestRate/12;
}
//取钱
public void withdraw(double amount){
if (balance>=amount){
balance-=amount;
return;
}
System.out.println("余额不足");
}
//存钱
public void deposit(double amount){
if (amount>=0){
balance+=amount;
}
}
}
public class AccountTest {
public static void main(String[] args) {
Account account= new Account(1122,20000,0.045);
account.withdraw(30000);
System.out.println(account.getBalance());
account.withdraw(1000);
System.out.println(account.getBalance());
account.withdraw(300);
System.out.println(account.getBalance());
System.out.println("月利率为: "+(account.getMonthlyinterest()*100)+"%");
}
}
public class CheckAccount extends Account{
private double overdraft;//可透支限额
public CheckAccount (int id, double balance, double annualInterestRate,double overdraft){
super(id,balance,annualInterestRate);
this.overdraft=overdraft;
}
public void withdraw(double amount){
if (getBalance()>=amount){
super.withdraw(amount);
}else if (overdraft>=amount-getBalance()){
setBalance(0);
overdraft-=(amount-getBalance());
}else {
System.out.println("超过可透支限额:");
}
}
public double getOverdraft() {
return overdraft;
}
public void setOverdraft(double overdraft) {
this.overdraft = overdraft;
}
}
public class CheckAccounttest {
public static void main(String[] args) {
CheckAccount account=new CheckAccount(1122,2000,0.045,5000);
account.withdraw(500);
System.out.println("账户余额: "+account.getBalance());
System.out.println("可透支额度:"+account.getOverdraft());
account.withdraw(1500);
System.out.println("账户余额: "+account.getBalance());
System.out.println("可透支额度:"+account.getOverdraft());
account.withdraw(4500);
System.out.println("账户余额: "+account.getBalance());
System.out.println("可透支额度:"+account.getOverdraft());
}
多态性
package duotai;
public class Animaltest {
public void func(Animal animal){//Animal animal=new Dog()
animal.eat();
animal.shout();
}
public static void main(String[] args) {
Animaltest animaltest=new Animaltest();
animaltest.func(new Dog());
}
}
class Animal{
public void eat(){
System.out.println("动物:进食");
}
public void shout(){
System.out.println("动物:叫");
}
}
class Dog extends Animal{
public void eat(){
System.out.println("狗吃骨头");
}
public void shout(){
System.out.println("汪!");
}
}
class Cat extends Animal{
public void eat(){
System.out.println("猫吃鱼");
}
public void shout(){
System.out.println("喵!");
}
}
向下转型
instanceof关键字
equals()方法
1.
package exer7;
public class OrderTest {
public static void main(String[] args) {
Order order1=new Order(11,"AA");
Order order2=new Order(22,"BB");
Order order3=new Order(22,"BB");
System.out.println(order1.equals(order2));
System.out.println(order2.equals(order3));
}
}
class Order{
private int orderId;
private String orderName;
public Order(int orderId, String orderName) {
this.orderId = orderId;
this.orderName = orderName;
}
public int getOrderId() {
return orderId;
}
public void setOrderId(int orderId) {
this.orderId = orderId;
}
public String getOrderName() {
return orderName;
}
public void setOrderName(String orderName) {
this.orderName = orderName;
}
public boolean equals(Object obj){
if (this==obj){
return true;
}
if (obj instanceof Order){
Order order=(Order) obj;
return this.orderId==order.orderId&&this.orderName.equals(order.orderName);
}
return false;
}
}
2.重写equals()
package exer7;
public class Mydatetest {
public static void main(String[] args) {
MyDate m1=new MyDate(14,13,1998);
MyDate m2=new MyDate(14,13,1998);
if (m1==m2){
System.out.println("m1==m2");
}else {
System.out.println("m1!=m2");
}
if (m1.equals(m2)){
System.out.println("m1 equals m2");
}else {
System.out.println("m1 not equals m2");
}
}
}
class MyDate{
private int day;
private int month;
private int year;
public MyDate(int day, int month, int year) {
this.day = day;
this.month = month;
this.year = year;
}
public int getDay() {
return day;
}
public void setDay(int day) {
this.day = day;
}
public int getMonth() {
return month;
}
public void setMonth(int month) {
this.month = month;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
@Override
public boolean equals(Object obj) {
if (this==obj){
return true;
}
if (obj instanceof MyDate){
MyDate myDate=(MyDate)obj;
return this.day==myDate.day&&this.month==myDate.month
&&this.year==myDate.year;
}
return false;
}
}
toString()方法
包装类
单元测试
包装类使用
基本数据类型-----》包装类
包装类-----》基本数据类型
自动装箱与自动拆箱
基本数据类型、包装类-----》String类型
String类型-----》基本数据类型、包装类
static关键字
类的加载,同时加载静态结构(属性、方法),创建对象后加载非静态结构
static练习
package Circletest;
//static关键词的应用
public class circleTest {
public static void main(String[] args) {
Circle c1=new Circle();
Circle c2=new Circle();
System.out.println(c1.getId());
System.out.println(c2.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;
}
}
package Account;
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.getInterestrate());
System.out.println(acct1.getMinMoney());
System.out.println(acct1.toString());
System.out.println(acct2.toString());
}
}
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 int getId() {
return id;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public double getBalance() {
return balance;
}
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;
}
@Override
public String toString() {
return "Account{" +
"pwd='" + pwd + '\'' +
", balance=" + balance +
'}';
}
}
单例设计模式
1.饿汉式
package singleton;
//单例设计模式就是采取一定的方法保证整个软件系统中,对某个类只能存在一个对象实例
public class singletonTest {
public static void main(String[] args) {
Bank bank1=Bank.getInstance();
}
}
//饿汉式
class Bank{
//1.私有化构造器,以避免在外部创建对象
private Bank(){
}
//2.内部创建静态的类对象
private static Bank instance=new Bank();
//3.提供公共静态的方法,返回类的对象
public static Bank getInstance(){
return instance;
}
}
2.懒汉式
package singleton;
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.声明当前静态类对象,没有初始化
private static order instance=null;
//3.声明public、static返回当前类对象的方法
public static order getInstance(){
if (instance==null){
instance=new order();
}
return instance;
}
}
理解main()方法
类的内部结构3:代码块(初始化块)
package daimakuai;
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();
}
}
class Person{
String name;
int age;
static String desc="人物画像";
//构造器
public Person(){
}
public Person(String name,int age){
this.age=age;
this.name=name;
}
//静态代码块
static {
System.out.println("hello,static block");
desc="人才画像";
}
//非静态代码块
{
System.out.println("hello,block");
eat();
}
//方法
public void eat(){
System.out.println("吃饭");
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
final关键字
抽象类
package Abstract;
public class AbstractTest {
public static void main(String[] args) {
//Person P1=new Person();//Person是抽象的; 无法实例化
student s1=new student("ppap",18);
System.out.println(s1.age);
s1.walk();
}
}
//抽象类
abstract class Person{
String name;
int age;
public Person(){
}
public Person(String name,int age){
this.age=age;
this.name=name;
}
//抽象方法
public abstract void eat();
//方法
public void walk(){
System.out.println("人走路");
}
}
class student extends Person{
public student(String name,int age){
super(name,age);
}
//子类需要重写全部方法
public void walk(){
System.out.println("人走路");
}
public void eat(){
System.out.println("吃");
}
}
package Employee;
class employeetest{
public static void main(String[] args) {
Manager manager= new Manager("库克",1001,5000,50000);
manager.work();
Commnemployee commnemployee=new Commnemployee();
commnemployee.work();
}
}
abstract class employee {
private String name;
private int id;
private double salary;
//构造器
public employee(){
}
public employee(String name, int id, double salary) {
this.name = name;
this.id = id;
this.salary = salary;
}
public abstract void work();
}
class Manager extends employee{
private double bonus;
public Manager(double bonus) {
this.bonus = bonus;
}
public Manager(String name, int id, double salary, double bonus) {
super(name, id, salary);
this.bonus = bonus;
}
public void work(){
System.out.println("管理员工,提高公司运行效率");
}
}
class Commnemployee extends employee{
public void work(){
System.out.println("员工在一线车间");
}
}
模版方法设计模式
package Test;
public class TemplateTest {
public static void main(String[] args) {
subTemplate t=new subTemplate();
t.spendtime();
}
}
abstract class Template{
//计算某段代码计算时间
public void spendtime(){
long start=System.currentTimeMillis();
code();//不确定的部分(易变的部分)
long end=System.currentTimeMillis();
System.out.println("花费时间为:"+(end-start));
}
public abstract void code();
}
class subTemplate extends Template{
public void code(){
//一千以内的质数
for (int i=2;i<=1000;i++){
boolean isflag=true;
for (int j=2;j<Math.sqrt(i);j++){
if (i%j==0){
isflag=false;
break;
}
}
if (isflag){
System.out.println("是质数");
}
}
}
}
package exe1;
public abstract class Employee {
private String mame;
private int number;
private Mydate birthday;
//抽象方法
public abstract double earnings();
//构造器
public Employee(String mame, int number, Mydate birthday) {
this.mame = mame;
this.number = number;
this.birthday = birthday;
}
//get/set
public String getMame() {
return mame;
}
public void setMame(String mame) {
this.mame = mame;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public Mydate getBirthday() {
return birthday;
}
public void setBirthday(Mydate birthday) {
this.birthday = birthday;
}
@Override
public String toString() {
return
"mame='" + mame + '\'' +
", number=" + number +
", birthday=" + birthday.toDateString();
}
}
package exe1;
public class SalariedEmployee extends Employee{
private double monthlysalary;
//构造器
public SalariedEmployee(String mame, int number, Mydate birthday) {
super(mame, number, birthday);
}
public SalariedEmployee(String mame, int number, Mydate birthday,double monthlysalary) {
super(mame, number, birthday);
this.monthlysalary=monthlysalary;
}
public double getMonthlysalary() {
return monthlysalary;
}
public void setMonthlysalary(double monthlysalary) {
this.monthlysalary = monthlysalary;
}
@Override
public double earnings() {
return monthlysalary;
}
@Override
public String toString() {
return "SalariedEmployee{" +super.toString()+"}";
}
}
package exe1;
public class houremployee extends Employee{
private int wage;//每小时工资
private int hour;//月工作的小时数
public houremployee(String mame, int number, Mydate birthday) {
super(mame, number, birthday);
}
public houremployee(String mame, int number, Mydate birthday,int wage,int hour) {
super(mame, number, birthday);
this.wage=wage;
this.hour=hour;
}
public int getWage() {
return wage;
}
public void setWage(int wage) {
this.wage = wage;
}
public int getHour() {
return hour;
}
public void setHour(int hour) {
this.hour = hour;
}
@Override
public double earnings() {
return wage*hour;
}
@Override
public String toString() {
return "houremployee{" +
super.toString()+
"}";
}
}
package exe1;
public class Mydate {
private int year;
private int month;
private int day;
public Mydate(int year, int month, int day) {
this.year = year;
this.month = month;
this.day = day;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public int getMonth() {
return month;
}
public void setMonth(int month) {
this.month = month;
}
public int getDay() {
return day;
}
public void setDay(int day) {
this.day = day;
}
public String toDateString() {
return "Mydate{" +
"year=" + year +
", month=" + month +
", day=" + day +
'}';
}
}
package exe1;
import java.util.Calendar;
import java.util.Scanner;
public class PayrollSystem {
public static void main(String[] args) {
//获取当前月份
//方式一:
// Scanner scanner=new Scanner(System.in);
// System.out.println("请输入当前月份:");
// int month=scanner.nextInt();//输入当前月份
//方式二:
Calendar calendar=Calendar.getInstance();
int month=calendar.get(Calendar.MONTH);
System.out.println(month);//一月为0
Employee emps[]=new Employee[2];
emps[0]=new SalariedEmployee("马森",1002,
new Mydate(1992,1,28),10000);
emps[1]=new houremployee("张伟",2002,
new Mydate(1991,2,6),60,240);
System.out.println(emps[1]);
for (int i=0;i<emps.length;i++){
System.out.println(emps[i]);
double salary= emps[i].earnings();
System.out.println("月工资为:"+salary);
if (month+1==emps[i].getBirthday().getMonth()){
System.out.println("生日快乐,奖励100元");
}
}
}
}
接口
package Interface;
public class interfaceTest {
public static void main(String[] args) {
System.out.println(Flyable.MAX_SPEED);
System.out.println(Flyable.MIN_SPEED);
Plane P=new Plane();
P.fly();
}
}
//定义接口
interface Flyable{
//接口中不能定义构造器,因此不可实例化
// public Flyable(){
// }
//全局常量
public static final int MAX_SPEED=7900;
int MIN_SPEED=1;//public static final可省略
//抽象方法
public abstract void fly();
void stop();//public abstract可省略
}
interface Attackable{
void attack();
}
//实现类
class Plane implements Flyable{
@Override
public void fly() {
System.out.println("通过引擎起飞");
}
@Override
public void stop() {
System.out.println("驾驶员减速停止");
}
}
class Bullet implements Flyable,Attackable{
@Override
public void fly() {
}
@Override
public void stop() {
}
@Override
public void attack() {
}
}
//****************多继承
interface AA{
void method1();
}
interface BB{
void method2();
}
interface CC extends AA,BB{
}
接口的举例
package Interface;
public class USBTest {
public static void main(String[] args) {
Computer com=new Computer();
//1.创建了接口的非匿名实现类的非匿名对象
Flash flash=new Flash();
com.transferData(flash);
//2.创建了接口的非匿名实现类的匿名对象
com.transferData(new Flash());
//3.创建了接口的匿名实现类的非匿名对象
USB phone=new USB(){
@Override
public void start() {
System.out.println("手机开始工作");
}
@Override
public void stop() {
System.out.println("手机结束工作");
}
};
com.transferData(phone);
//4.创建了接口的匿名实现类的匿名对象
com.transferData(new USB() {
@Override
public void start() {
System.out.println("mp3开始工作");
}
@Override
public void stop() {
System.out.println("mp3结束工作");
}
});
}
}
class Computer{
//方法
public void transferData(USB usb){//USB flash=new Flash()多态性
usb.start();
System.out.println("具体传输数据的细节");
usb.stop();
}
}
//接口
interface USB{
void start();
void stop();
}
//实现类
class Flash implements USB{
@Override
public void start() {
System.out.println("U盘开始工作");
}
@Override
public void stop() {
System.out.println("U盘停止工作");
}
}
class Printer implements USB{
@Override
public void start() {
System.out.println("打印机开始工作");
}
@Override
public void stop() {
System.out.println("打印机停止工作");
}
}
接口的应用(代理模式)
package Interface;
public class NetworkTest {
public static void main(String[] args) {
Server server=new Server();
ProxyServer proxyServer = new ProxyServer(server);
proxyServer.browse();
}
}
interface Network{
public void browse();//浏览方法
}
//被代理类
class Server implements Network{
@Override
public void browse() {
System.out.println("真实的服务器访问网络");
}
}
//代理类
class ProxyServer implements Network{
private Network work;
//构造器
public ProxyServer(Network work){
this.work=work;
}
public void check(){
System.out.println("检查完成");
}
@Override
public void browse() {
check();//实现代理类的功能并且实现被代理类的功能
work.browse();
}
}
接口的应用(工厂模式)
package exe1;
public interface CompareObject {
public int compareTo(Object O);
}
public class Circle {
private double radius;
public Circle(){
super();
}
public Circle(double radius) {
this.radius = radius;
}
public double getRadius() {
return radius;
}
public void setRadius(double radius) {
this.radius = radius;
}
}
public class CompareableCircle extends Circle implements CompareObject {
//构造器
public CompareableCircle (double radius){
super(radius);
}
public int compareTo(Object O){
if (this==O){
return 0;
}
if (O instanceof CompareableCircle){
CompareableCircle C=(CompareableCircle)O;
if (this.getRadius()>C.getRadius()){
return 1;
}else if (this.getRadius()<C.getRadius()){
return -1;
}else {
return 0;
}
}else {
return 0;
}
}
}
public class CompareableCircleTest {
public static void main(String[] args) {
CompareableCircle c1=new CompareableCircle(3.4);
CompareableCircle c2=new CompareableCircle(3.6);
int compare=c1.compareTo(c2);
if (compare>0){
System.out.println("c1大");
}else if (compare<0){
System.out.println("c2大");
}else if (compare==0){
System.out.println("一样大");
}else {
System.out.println("错误");
}
}
}
JDK8新特性
内部类
六、异常
异常处理
try-catch-finally
public class FinallyTest {
public void test(){
try{
int a=10;
int b=0;
System.out.println(a/b);//异常
System.out.println("我很棒1!");
}catch (ArithmeticException e){
e.printStackTrace();//打印异常原因
}catch (Exception e){
e.printStackTrace();
} finally{
System.out.println("我很棒2!");//声明
}
}
}
throws
package exe2;
public class throwsTest {
public static void main(String[] args) {
try {
test2();
} catch (Exception e){
e.printStackTrace();
}
System.out.println("异常展现完毕");
}
public static void test1() throws Exception {
int a=10;
int b=0;
System.out.println(a/b);
}
public static void test2() throws Exception{
test1();
System.out.println("异常后面代码不再执行");
}
}
手动抛出异常throw
package exe2;
public class throwTest {
public static void main(String[] args) {
Student s=new Student();
try {
s.regist(-1001);
System.out.println(s);
}catch (Exception e){
// e.printStackTrace();
System.out.println(e.getMessage());
}
}
}
class Student{
private int id;
public void regist(int id)throws Exception{
if (id>0){
this.id=id;
}else {
//手动抛出异常
throw new Exception("您输入的数据非法");
}
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
'}';
}
}
用户自定义异常类
package exe2;
//如何自定义异常类?
//1.继承现有的异常结构,RuntimeException、Exception
//2.提供全局常量:serialVersionUID
//3.提供重载的构造器
public class MyException extends RuntimeException{
static final long serialVersionUID = -7034897190745766939L;
public MyException(){
}
public MyException(String msg){
super(msg);
}
}
package exer;
//自定义异常类
public class EcDef extends Exception{
static final long serialVersionUID = -33871546387L;
//定义构造器
public EcDef(){
}
public EcDef(String msg){
super(msg);
}
}
public class EcmDef {
public static void main(String[] args) {
try{
int i=Integer.parseInt(args[0]);
int j=Integer.parseInt(args[1]);
int result=ecm(i,j);
System.out.println(result);
}catch (NumberFormatException e){
System.out.println("数据类型不一致");
}catch (ArrayIndexOutOfBoundsException e){
System.out.println("缺少命令行参数");
}catch (ArithmeticException e){
System.out.println("算数异常");
}catch (EcDef e){
System.out.println(e.getMessage());
}
}
public static int ecm(int i,int j) throws EcDef{
if (i<0||j<0){
throw new EcDef("分子分母为负数了");//抛出异常
}
return i/j;
}
}
项目三