DevOps开发运维
成长之路

Java面向对象编程(中级)


ArrayTest.java

import java.util.Scanner;

public class ArrayTest {
    public static void main(String[] args) {
        Scanner myScanner = new Scanner(System.in);
        //快捷键自动分配变量名,在后面加.var
//        Scanner scanner = new Scanner(System.in);
//        Scanner scanner1 = new Scanner(System.in)
//        MyTools myTools = new MyTools();
        MyTools mt = new MyTools();
        int[] arr = {10, 2, -1, 8, 32};
        //定位到方法ctrl + B
        mt.bubble(arr);
        //输出排序后的arr,引用传递
        System.out.println("排序后的arr");
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
        //注意
        //在idea当我们run一个文件时,会先编译成.class文件
    }
}
//查看类的继承关系ctrl+H
class Person {
    String name;
    int age;
    //构造器-快捷键alt+insert
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    } 
}
//创建一个类MyTools,编写一个方法,可以完成对int数组冒泡排序的功能
//从小到大
class MyTools {

    public void bubble(int[] arr) {
        //冒泡排序
        int temp = 0;
        for (int i = 0; i < arr.length; i++) {//外层循环次数arr.length-1
            for (int j = 0; j < arr.length - 1 - i; j++) { 
                if (arr[j] > arr[j + 1]) {
                    temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }

            }
        }
    }
}


TestTemplate.java

public class TestTemplate {
    //模板快捷键
    //输出main
    public static void main(String[] args) {
        //输入sout
        System.out.println();
        //输入fori
//        for (int i = 0; i < ; i++) {
//
//        }
    }
}


Test.java

package com.use;

import com.xiaoqiang.Dog;

public class Test {
    public static void main(String[] args) {
        Dog dog = new Dog();
        System.out.println(dog);//com.xiaoqiang.Dog@1540e19d

        com.xiaoming.Dog dog1 = new com.xiaoming.Dog();
        System.out.println(dog1);//com.xiaoming.Dog@677327b6

    }
}
com.xiaoming.Dog.java
package com.xiaoming;

public class Dog {
}

com.xiaoqiang.Dog.java
package com.xiaoqiang;

public class Dog {
}


Import01.java

package com.hspedu.pkg;

import java.util.Arrays;

//注意
//需要使用到哪个类,就导入哪个类即可,不建议使用*导入
//表示只会引入java.util包下的Scanner
import java.util.Scanner;
//表示引入java.util包下的所有类
//import java.util.*;
public class Import01 {
    public static void main(String[] args) {
        //使用系统系统的Arrays完成数组排序
        int[] arr = {-1,20,2,13,3};
        //对上面数组进行排序
        //传统方法,自己编写排序(冒泡)
        //系统提供了相关的类,可以方便完成Arrays
        Arrays.sort(arr);
        //输出排序结果
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
    }
}


PkgDetail.java

//package的作用是声明当前类所在的包,需要放在类(或者文件)的最上面
//一个类中最多只有一句package
package com.hspedu.pkg;
//import指令位置放在package的下面,在类定义之前,可以有多句且没有顺序要求
import java.util.Arrays;
import java.util.Scanner;

//类定义
public class PkgDetail {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int[] arr = {0,-1,1};
        Arrays.sort(arr);
        for (int i = 0; i < arr.length; i++) {
            System.out.println(arr[i] + " ");
        }
    }
}


com.hspedu.modifier.A.java

package com.hspedu.modifier;
//只有默认和public才能修饰类
//修饰符可以用来修饰类中的属性和成员方法以及类
public class A {
    //四个属性,用不同访问修饰符修饰
    public int n1 = 100;
    protected int n2 = 200;
    int n3 = 300;
    private int n4 = 400;
    public void m1() {
        //在同一个类下,可以访问public,protected和默认,private修饰的属性
        System.out.print("n1=" + n1 + " ");
        System.out.print("n2=" + n2 + " ");
        System.out.print("n3=" + n3 + " ");
        System.out.print("n4=" + n4 + " ");
    }
    protected void m2(){}
    void m3(){}
    private void m4(){}
    public void hi(){
//在同一个类下,可以访问public,protected和默认,private修饰的方法
        m1();
        m2();
        m3();
        m4();
    }
}
com.hspedu.modifier.B.java
package com.hspedu.modifier;

public class B {
    public void say() {
        A a = new A();
        //在同一个包下,可以访问public,protected和默认修饰的属性
        System.out.print("\nn1=" + a.n1 + " ");
        System.out.print("n2=" + a.n2 + " ");
        System.out.print("n3=" + a.n3 + " ");
        //n4是private的访问控制,无法访问
        //System.out.println("n1=" + a.n4);//错误不能调用
 //在同一个包下,可以访问public,protected和默认修饰的方法
        a.m1();
        a.m2();
        a.m3();
        //a.m4();//错误不能调用

    }
}
com.hspedu.modifier.Test.java
package com.hspedu.modifier;

public class Test {
    public static void main(String[] args) {
        A a = new A();
        a.m1();
        B b = new B();
        b.say();
    }
}
//只有默认和public可以修饰类
class Tiger {}
com.hspedu.pkg.Test.java
package com.hspedu.pkg;

import com.hspedu.modifier.A;

public class Test {
    public static void main(String[] args) {
        A a = new A();
        //在不同包下,可以访问public修饰的属性
        //不能访问protected,默认private修饰的属性或方法
        System.out.println("n1=" + a.n1);
//        System.out.println("n2=" + a.n2);//错误不能调用
//        System.out.println("n3=" + a.n3);//错误不能调用
//        System.out.println("n4=" + a.n4);//错误不能调用
//在不同包下,可以访问public修饰的方法,不能访问a.m2(),a.m3(),a.m4()
        a.m1();
    }
}


com.hspedu.encap.Encapsulation01.java

package com.hspedu.encap;

public class Encapsulation01 {
    public static void main(String[] args) {
        //如果要使用快捷键alt+r,需要先配置主类
        Person person = new Person();
        person.setName("jack");
        person.setAge(30);
        person.setSalary(30000);
        System.out.println(person.info());
        System.out.println(person.getSalary());
    }
}

class Person {
    public String name;//名字公开
    private int age;//年龄私有
    private double salary;//...

    //自己写setxxx和getxxx太慢,使用快捷键
    //然后根据要求来完善我们的代码.

    public String getName() {
        return name;
    }

    public void setName(String name) {
        //加入对数据的校验,相当于增加了业务逻辑
        if(name.length() >= 2 && name.length() <= 6){ 
              this.name = name; 
        }else{ 
              System.out.println("名字的长度不对,需要(2-6)个字符,默认名字"); 
              this.name = "无名人"; 
        } 
   } 
    public int getAge(){ 
       return age;
    }
    public void setAge(int age) {
        if(age >= 1 && age <= 120){
            this.age = age;
        }else{
            System.out.println("你设置的年龄不对,年龄需要在1-120,默认年龄18");
            this.age = 18;//给一个默认年龄
        }
    }

    public double getSalary() {
        //可以这里增加对当前对象的权限判断
        return salary;
    }

    public void setSalary(double salary) {
        this.salary = salary;
    }
    //写一个方法,返回属性信息
    public String info(){
        return "信息为name=" + name + " age=" + age + " 薪水=" + salary;
    }
}


com.hspedu.encap.Encapsulation01.java

package com.hspedu.encap;

public class Encapsulation01 {
    public static void main(String[] args) {
        //如果要使用快捷键alt+r,需要先配置主类
        Person person = new Person();
        person.setName("jack");
        person.setAge(30);
        person.setSalary(30000);
        System.out.println(person.info());
        System.out.println(person.getSalary());
//        如果直接使用构造器指定属性
        Person smith = new Person("smith", 80, 50000);
        System.out.println("===smith的信息===");
        System.out.println(smith.info());
    }
}

class Person {
    public String name;//名字公开
    private int age;//年龄私有
    private double salary;//...
    //构造器alt+insert
    public Person(){
    }
    //有3个属性的构造器
    public Person(String name, int age, double salary) {
        this.name = name;
        this.age = age;
        this.salary = salary;
        //可以将set方法写在构造器中,这样仍然可以验证
        setName(name);
        setAge(age);
        setSalary(salary);
    }
    //自己写setxxx和getxxx太慢,使用快捷键
    //然后根据要求来完善我们的代码.

    public String getName() {
        return name;
    }

    public void setName(String name) {
        //加入对数据的校验,相当于增加了业务逻辑
        if(name.length() >= 2 && name.length() <= 6){ 
            this.name = name; 
        }else{ 
            System.out.println("名字的长度不对,需要(2-6)个字符,默认名字"); 
            this.name = "无名人"; 
        } 
     } 
    public int getAge(){ 
        return age; 
    } 
    public void setAge(int age) { 
      if(age >= 1 && age <= 120){
            this.age = age;
        }else{
            System.out.println("你设置的年龄不对,年龄需要在1-120,默认年龄18");
            this.age = 18;//给一个默认年龄
        }
    }

    public double getSalary() {
        //可以这里增加对当前对象的权限判断
        return salary;
    }

    public void setSalary(double salary) {
        this.salary = salary;
    }
    //写一个方法,返回属性信息
    public String info(){
        return "信息为name=" + name + " age=" + age + " 薪水=" + salary;
    }
}


com.hspedu.encap.Account.java

package com.hspedu.encap;

public class Account {
    //为了封装,将3个属性设置为private
    private String name;
    private double balance;
    private String pwd;
    //两个构造器
    public Account(){
    }

    public Account(String name, double balance, String pwd) {
        this.setName(name);
        this.setBalance(balance);
        this.setPwd(pwd);
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        if(name.length() >= 2 && name.length() <= 4){ 
            this.name = name; 
       }else{ 
           System.out.println("名字输入错误,姓名要求(长度为2,3,4),默认值无名"); 
           this.name = "无名"; 
       } 
   } 
    public double getBalance() { 
        return balance; 
    } 
    public void setBalance(double balance) { 
        if(balance > 20){
            this.balance = balance;
        }else{
            System.out.println("余额必须>20,默认为0");
        }
    }

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        if(pwd.length() == 6){
            this.pwd = pwd;
        }else{
            System.out.println("密码必须是6位,默认密码为000000");
            this.pwd = "000000";
        }
    }
    //显示账号信息
    public void showInfo(){
        //可以增加一个权限校验
        System.out.println("账号信息 name=" + name + " 余额=" + balance + " 密码=" + pwd);
//        if() {
//            System.out.println("账号信息 name=" + name + " 余额=" + balance + " 密码=");
//        }else{
//            System.out.println("你无权查看...");
//        }
    }
}
com.hspedu.encap.AccountTest.java
package com.hspedu.encap;

public class AccountTest {
    public static void main(String[] args) {
        //创建Account
        Account account = new Account("jack",60,"123456");
        //Account account = new Account();
        //account.setName("jack");
        //account.setBalance(60);
        //account.setPwd("123456");
        account.showInfo();
    }
}


com.hspedu.extend.Pupil.java

package com.hspedu.extend;

//小学生->模拟小学生考试的情况
public class Pupil {
    public String name;
    public int age;
    private double score;

    public void setScore(double score) {
        this.score = score;
    }
    public void testing(){
        System.out.println("小学生" + name + "正在考小学数学...");
    }
    public void showInfo() {
        System.out.println("小学生名" + name + "年龄" + age + "分数" +score);
    }
}

com.hspedu.extend.Graduate.java
package com.hspedu.extend;
//大学生考试情况-模拟大学生类
public class Graduate {
    public String name;
    public int age;
    private double score;

    public void setScore(double score) {
        this.score = score;
    }

    public void testing(){
        System.out.println("大学生" + name + "正在考大学数学...");
    }

    public void showInfo() {
        System.out.println("大学生" + name + "年龄" + age + "分数" +score);
    }
}
com.hspedu.extend.Extends01.java
package com.hspedu.extend;

public class Extends01 {
    public static void main(String[] args) {
        Pupil pupil = new Pupil();
        pupil.name = "银角大王";
        pupil.age = 10;
        pupil.testing();
        pupil.setScore(60);
        pupil.showInfo();

        System.out.println("=====");
        Graduate graduate = new Graduate();
        graduate.name = "金角大王";
        graduate.age = 22;
        graduate.testing();
        graduate.setScore(100);
        graduate.showInfo();
    }
}


com.hspedu.extend.improve_.Pupil.java

package com.hspedu.extend.improve_;

public class Pupil extends Student{
    public void testing(){
        System.out.println("小学生" + name + "正在考小学数学...");
    }
}
com.hspedu.extend.improve_.Graduate.java
package com.hspedu.extend.improve_;

public class Graduate extends Student{
    public void testing(){
        System.out.println("大学生" + name + "正在考大学数学...");
    }
}
com.hspedu.extend.improve_.Student.java
package com.hspedu.extend.improve_;

//父类
public class Student {
    //共有属性
    public String name;
    public int age;
    private double score;
    //共有方法
    public void setScore(double score) {
        this.score = score;
    }

    public void showInfo() {
        System.out.println("学生" + name + "年龄 " + age + " 分数 " +score);
    }
}
com.hspedu.extend.improve_.Extends01.java
package com.hspedu.extend.improve_;

import com.hspedu.extend.Graduate;
import com.hspedu.extend.Pupil;

public class Extends01 {
    public static void main(String[] args) {
        com.hspedu.extend.Pupil pupil = new Pupil();
        pupil.name = "银角大王~";
        pupil.age = 11;
        pupil.testing();
        pupil.setScore(50);
        pupil.showInfo();

        System.out.println("=====");
        com.hspedu.extend.Graduate graduate = new Graduate();
        graduate.name = "金角大王~";
        graduate.age = 23;
        graduate.testing();
        graduate.setScore(80);
        graduate.showInfo();
    }
}


com.hspedu.encap.TopBase.java

package com.hspedu.encap;

public class TopBase {//父类是Object
    public TopBase() {
        System.out.println("父类的父类构造器TopBase()被调用");
    }
}
com.hspedu.extend.Base.java
package com.hspedu.extend;

import com.hspedu.encap.TopBase;

public class Base extends TopBase {//父类
    //4个属性
    public int n1 = 100;
    protected int n2 = 200;
    int n3 = 300;
    private int n4 = 400;

    public Base() {//父类的无参构造器
        System.out.println("父类Base()构造器被调用...");
    }
    public Base(String name,int age){//父类的有参构造器1
        System.out.println("父类Base(String name,int age)被调用...");
    }
    public Base(String name){//父类的有参构造器2
        System.out.println("父类Base(String name)被调用...");
    }

    //父类提供public方法,返回n4
    public int getN4(){
        return n4;
    }
    public void test100() {
        System.out.println("test100");
    }
    protected void test200() {
        System.out.println("test200");
    }
    void test300() {
        System.out.println("test300");
    }
    private void test400() {
        System.out.println("test400");
    }
    public void callTest400(){
        test400();
    }
}
com.hspedu.extend.Sub.java
package com.hspedu.extend;

import java.util.Arrays;

//输入ctrl + H 可以看到类的继承关系
public class Sub extends Base {//子类

    public Sub(String name,int age){
        //1.调用父类的无参构造器,或者什么都不写
        //super();//父类的无参构造器
        //2.调用父类的Base(String name)构造器
        //细节4:如果希望指定去调用父类的某个构造器,则显式的调用一下:super(参数列表)
        //super("hsp");
        //3.调用父类的Base(String name,int age)构造器
        super("hsp",11);
        //细节5:super在使用时,必须放在构造器的第一行(super只能在构造器中使用)
        //细节6:super()和this()都只能放在构造器第一行,因此这两个方法不能共存在一个构造器
        System.out.println("子类Sub(String name,int age)构造器被调用....");
    }

    public Sub() {//子类的无参构造器
        //细节2:默认隐藏调用父类的无参构造器
        //super();
        super("smith",10);
        System.out.println("子类Sub()构造器被调用....");
    }
    //细节3-1:当创建子类对象时,不管使用子类的哪个构造器,默认情况下总会去调用父类的无参构造器
    public Sub(String name) {
    //细节3-2:如果父类没有提供无参构造器,则必须在子类的构造器中用super去指定使用
    //父类的哪个构造器完成对父类的初始化工作,否则,编译不会通过
        super("tom",30);
        System.out.println("子类Sub(String name) 构造器被调用....");
    }
    public void sayOk() {//子类方法
        //细节1:非私有的属性和方法可以在子类直接访问
        //私有的属性和方法不可以在子类直接访问
        System.out.println(n1 + " " + n2 + " " + n3 + " ");
        test100(); 
        test200(); 
        test300();
        //test400();//错误
        //属性n4无法输出,要通过父类提供的公共方法去访问
        System.out.println("n4=" + getN4());
        //要通过父类提供的公共方法去访问
        callTest400();
    }
}
com.hspedu.extend.ExtendsDetail.java
package com.hspedu.extend;

public class ExtendsDetail {
    public static void main(String[] args) {
//        System.out.println("==第1个对象==");
//        Sub sub = new Sub();//创建子类对象sub
//        System.out.println("==第2个对象==");
//        Sub sub2 = new Sub("jack");//创建子类对象sub2
        System.out.println("==第3个对象==");
        Sub sub3 = new Sub("king",10);//创建子类对象sub3
        //sub.sayOk();
    }
}


com.hspedu.extend.ExtendsTheory.java

package com.hspedu.extend;
/**
讲解继承的本质
*/
public class ExtendsTheory {
    public static void main(String[] args) {
        Son son = new Son();//内存的布局
        //1.首先看子类是否有该属性
        //2.如果子类有这个属性,并且可以访问(比如private 私有)
        //3.如果子类没有这个属性,就看父类有没有这个属性(如果父类有该属性,并且可以访问,就返回信息...)
        //4.如果父类没有就按照3.的规则,就继续找上级父类,直到Object...
        System.out.println(son.name);//返回的是大头儿子
//        System.out.println(son.age);//返回的是39
        System.out.println(son.getAge());//返回的是39
        System.out.println(son.hobby);//返回的是旅游
    }
}

class Grandpa {//爷类Grandpa
    String name = "大头爷爷";
    String hobby = "旅游";
}
class Father extends Grandpa {//父类Father
    String name = "大头爸爸";
    private int age = 39;

    public int getAge() {
        return age;
    }
}
class Son extends  Father {//子类Son
    String name = "大头儿子";
}


com.hspedu.extend.exercise.ExtendsExercise01.java

package com.hspedu.extend.exercise;

public class ExtendsExercise01 {
    public static void main(String[] args) {
        B b = new B();
/**
 * 结果
 * a
 * b name
 * b
 */
    }
}

class A {
    A() {
        System.out.println("a");
    }

    A(String name) {
        System.out.println("a name");
    }
}

class B extends A {
    B() {
        this("abc");//有了this以后就没有super()了
        System.out.println("b");
    }

    B(String name) {
         //解题关键:分析出有默认的super();
         System.out.println("b name"); } 
    }


com.hspedu.extend.exercise.ExtendsExercise02.java

package com.hspedu.extend.exercise;

public class ExtendsExercise02 {
    public static void main(String[] args) {
        C c = new C();
/**
 * 结果:
 * 我是A类
 * hahah我是B类的有参构造器
 * 我是C类的有参构造
 * 我是C类的无参构造
 * */ 
    }
}

class A{//A类
    public A() {
        System.out.println("我是A类");
    }
}

class B extends A{//B类,继承A类
    public B(){
        System.out.println("我是B类的无参构造器");
    }
    public B(String name){
        //解题关键:分析出有默认的super();
        System.out.println(name + "我是B类的有参构造器");
    }
}

class C extends B{
    public C(){
        this("hello");
        System.out.println("我是C类的无参构造");
    }
    public C(String name){
        super("hahah");
        System.out.println("我是c类的有参构造");
    }
}


com.hspedu.extend.exercise.Computer.java

package com.hspedu.extend.exercise;

public class Computer {
    private String cpu;
    private int memory;
    private int disk;

    public Computer(String cpu, int memory, int disk) {
        this.cpu = cpu;
        this.memory = memory;
        this.disk = disk;
    }

    public String getDetails(){
        return " cpu=" + cpu + " memory=" + memory + " disk=" + disk;
    }

    public String getCpu() {
        return cpu;
    }

    public void setCpu(String cpu) {
        this.cpu = cpu;
    }

    public int getMemory() {
        return memory;
    }

    public void setMemory(int memory) {
        this.memory = memory;
    }

    public int getDisk() {
        return disk;
    }

    public void setDisk(int disk) {
        this.disk = disk;
    }
}
com.hspedu.extend.exercise.PC.java
package com.hspedu.extend.exercise;

public class PC extends Computer{
    private String brand;
    //这里IDEA 根据继承的规则,自动把构造器的调用写好
    //这里也体现出继承的一个基本设计的基本思想,父类的构造器完成父类属性初始化
    //子类的构造器就完成子类的属性初始化
    public PC(String cpu, int memory, int disk, String brand) {
        super(cpu, memory, disk);
        this.brand = brand;
    }

    public String getBrand() {
        return brand;
    }

    public void setBrand(String brand) {
        this.brand = brand;
    }
    public void printInfo() {
        System.out.println("PC信息=");
        //调用父类的getDetails方法,得到相关属性...
        System.out.println(getDetails() + " brand=" + brand);
//      System.out.println(getCpu() + getDisk() + getMemory() + getBrand());
    }
}

com.hspedu.extend.exercise.NotePad.java
package com.hspedu.extend.exercise;

public class NotePad extends Computer{
    private String color;

    public NotePad(String cpu, int memory, int disk, String color) {
        super(cpu, memory, disk);
        this.color = color;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }
    public void printInnfo() {
        System.out.println("PC信息=");
        System.out.println(getDetails() + " color=" + color);
    }
}
com.hspedu.extend.exercise.ExtendsExercise03.java
package com.hspedu.extend.exercise;

public class ExtendsExercise03 {
    public static void main(String[] args) {
        PC pc = new PC("intel",16,500,"IBM");
        pc.printInfo();
        NotePad notepad = new NotePad("mac",24,1000,"black");
        notepad.printInnfo();
    }
}


com.hspedu.super_.B.java

package com.hspedu.super_;

public class B extends A {

    public int n1 = 888;
    //编写测试方法
    public void test() {
        //细节3:Super的访问不限于直接父类,如果爷爷类和本类中有同名的成员,也可以使用super
        //去访问爷爷类的成员;如果多个基类(上级类)中都有同名的成员,使用super访问遵循就近原则
        //A->B->C,当然也需要遵守访问权限的相关规则
        System.out.println("super.n1=" + super.n1);
        super.cal();
    }
    //语法1:访问父类的属性,但不能访问父类的private属性 [案例]super。属性名
    public void hi() {
        //super.n4为父类的private属性不能访问
        System.out.println(super.n1 + " " + super.n2 + " " +super.n3 /*+ super.n4*/);
    }
    //语法2:访问父类的方法,不能访问父类的private方法[案例] super。方法名(参数列表)
    public void ok(){
        super.test100();
        super.test200();
        super.test300();
        //super.test400();父类的private方法不能访问
    }
    //语法3:访问父类的构造器:super(参数列表);只能放在构造器的第一句,只能出现一句:
    public B(){
//        super();
//        super("jack");
        super("jack",10);
    }
    public void cal() {
        System.out.println("B类的cal()方法...");
    }
    public void sum() {
        //细节1:调用父类的构造器的好处(分工明确,父类属性由父类初始化,子类的属性由子类初始化)
        System.out.println("B类的sum()");
        //细节2-1:希望调用父类A的cal方法
        //这时,因为子类B没有cal方法,因此可以使用下面三种方式:
        //找cal方法时,顺序是:
        //1.先找本类,如果有,则调用
        //2.如果没有,则找父类(如果有并可以调用则调用)
        //3.如果父类没有,则继续找父类的父类,整个规则就是一样的。
        //提示:如果查找方法的过程中,找到了,但是不能访问,则报错
        //     如果查找方法的过程中,没有找到,则提示方法不存在
        cal();
        this.cal();//等价于cal()
        super.cal();//直接进入上面的第2步找父类,其他规则一样
        /**
         * 结果:
         * B类的sum()
         * B类的cal()方法...
         * B类的cal()方法...
         * A类的cal()方法...
         * */
        //细节2-2:演示访问属性的规则
        //n1和this查找的规则是
        //1.先找本类,如果有,则调用
        //2.如果没有,则找父类(如果有并可以调用则调用)
        //3.如果父类没有,则继续找父类的父类,整个规则就是一样的。
        //提示:如果查找属性的过程中,找到了,但是不能访问,则报错
        //     如果查找属性的过程中,没有找到,则提示属性不存在
        System.out.println(n1);
        System.out.println(this.n1);
        //super.n1的顺序是直接找父类,其他的规则一样
        System.out.println(super.n1);
        /**
         * 结果:
         * 888
         * 888
         * 100
         * */
    }
}
com.hspedu.super_.A.java
package com.hspedu.super_;

public class A extends Base{
    //4个属性
    public int n1 = 100;
    protected int n2 = 200;
    int n3 = 300;
    private int n4 = 400;

    public A(){}
    public A(String name) {}
    public A(String name,int age){}

    public void cal() {
        System.out.println("A类的cal()方法...");
    }
    public void test100() {

    }

    protected void test200() {

    }

    void test300() {

    }

    private void test400() {

    }
}
com.hspedu.super_.Base.java
package com.hspedu.super_;

public class Base {
    public int n1 = 999;
    public int age = 111;
    public void cal() {
        System.out.println("Base类的cal()方法...");
    }
    public void eat() {
        System.out.println("Base类中eat()方法...");
    }
}
com.hspedu.super_.Super01.java
package com.hspedu.super_;

public class Super01 {
    public static void main(String[] args) {
        B b = new B();//子类对象
//        b.sum();
        b.test();
    }
}


com.hspedu.override_.Dog.java

package com.hspedu.override_;

public class Dog extends Animal{
    //细节1:子类的方法的形参列表,方法名称要和父类方法的形参列表,方法名称完全一样
    //1.因为Dog是Animal子类
    //2.Dog的cry方法和Animal的cay()方法定义形式一样(名称,返回类型,参数)
    //3.Dog的cry()方法重写了Animal的cry()方法
    public void cry() {
        System.out.println("小狗汪汪叫");
    }
    //细节2:子类方法的返回类型和父类返回类型一样
    //或者是父类返回类型的子类,比如父类返回类型是Object,子类方法返回类型是String
    public String m1(){
        return null;
    }
    //细节3:子类方法不能缩小父类方法的访问权限
    //public > protected > 默认 > private
    public void eat() {

    }
}
com.hspedu.override_.Animal.java
package com.hspedu.override_;

public class Animal {
    public void cry() {
        System.out.println("动物叫唤...");
    }

    public Object m1() {
        return null;
    }

    protected void eat() {

    }
}
com.hspedu.override_.Override01.java
package com.hspedu.override_;

public class Override01 {
    public static void main(String[] args) {
        //演示方法重写的情况
        Dog dog = new Dog();
        dog.cry();//小狗汪汪叫

    }
}

 


com.hspedu.override_.Student.java

package com.hspedu.override_;
//编写一个Student类,继承Person类,增加id、score属性/private
//以及构造器,定义say方法(返回自我介绍的信息)
public class Student extends Person {
    private int id;
    private double score;

    public Student(String name, int age, int id, double score) {
        super(name, age);//调用父类构造器
        this.id = id;
        this.score = score;
    }
    //say方法
    public String say(){//体现super好处,代码复用
        return super.say() + ",id是" + id + ",分数是" + score;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public double getScore() {
        return score;
    }

    public void setScore(double score) {
        this.score = score;
    }
}

com.hspedu.override_.Person.java
package com.hspedu.override_;
//编写一个Person类,包括属性/private(name、age),构造
// 器,方法say(返回自我介绍的字符串)
public class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String say(){
        return "我的名字是:" + name + ",我的年龄是" + age;
    }

}
com.hspedu.override_.OverrideExercise.java
package com.hspedu.override_;

public class OverrideExercise {
    //在main中分别创建Person和Student对象,调用say方法输出自我介绍
    public static void main(String[] args) {
        Person jack = new Person("jack",10);
        System.out.println(jack.say());
        Student smith = new Student("smith",19,144564,92.8);
        System.out.println(smith.say());
    }

}


com.hspedu.poly_.Animal.java

package com.hspedu.poly_;

public class Animal {

    private String name;

    public Animal(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
com.hspedu.poly_.Cat.java
package com.hspedu.poly_;

public class Cat extends Animal {
    public Cat(String name) {
        super(name);
    }
}
com.hspedu.poly_.Dog.java
package com.hspedu.poly_;

public class Dog extends Animal {
    public Dog(String name) {
        super(name);
    }
}
com.hspedu.poly_.Fish.java
package com.hspedu.poly_;

public class Fish extends Food {

    public Fish(String name) {
        super(name);
    }

}
com.hspedu.poly_.Bone.java
package com.hspedu.poly_;

public class Bone extends Food {

    public Bone(String name) {
        super(name);
    }
}
com.hspedu.poly_.Food.java
package com.hspedu.poly_;

public class Food {
    private String name;

    public Food(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
com.hspedu.poly_.Master.java
package com.hspedu.poly_;

public class Master {
    private String name;

    public Master(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    //完成主人给小狗喂食骨头
    public void feed(Dog dog,Bone bone){
        System.out.println("主人" + name + "给" + dog.getName() + "吃" + bone.getName());
    }
    //完成主人给小猫喂食黄花鱼
    public void feed(Cat cat,Fish fish){
        System.out.println("========");
        System.out.println("主人" + name + "给" + cat.getName() + "吃" + fish.getName());
    }
    //如果动物很多,食物很多
    //feed方法很多,不利于管理和维护
    //Pig --> Rice
    //Tiger --> meat
    //...
}
com.hspedu.poly_.poly01.java
package com.hspedu.poly_;

public class poly01 {
    public static void main(String[] args) {
        Master tom = new Master("tom");
        Dog dog1 = new Dog("大黄狗");
        Bone bone1 = new Bone("大棒骨");
        tom.feed(dog1,bone1);

        Cat cat1 = new Cat("小花猫");
        Fish fish1 = new Fish("黄花鱼");
        tom.feed(cat1,fish1);


    }
}


com.hspedu.poly_.PloyMethod.java

package com.hspedu.poly_;

public class PloyMethod {
    public static void main(String[] args) {
        //方法重载体现多态
        A a = new A();
        //传入不同的参数,就会调用不同的sum方法,就体现多态
        System.out.println(a.sum(10,20));
        System.out.println(a.sum(20,30,40));
        //方法重写体现多态
        B b = new B();
        a.say();
        b.say();

    }
}

class B {//父类
    public void say() {
        System.out.println("B say()方法被调用...");
    }
}

class A extends B {//子类
    public int sum(int n1,int n2) {//和下面sum构成重载
        return n1 + n2;
    }
    public int sum(int n1, int n2, int n3){
        return n1 + n2 + n3;
    }
    public void say() {
        System.out.println("A say()方法被调用...");
    }
}

Animal.java

package com.hspedu.poly_.objpoly_;

public class Animal {
    public void cry(){
        System.out.println("Animal cry()动物再叫...");
    }
}

Cat.java

package com.hspedu.poly_.objpoly_;

public class Cat extends Animal{
    public void cry(){
        System.out.println("Cat cry()小猫喵喵叫...");
    }
}

Dog.java

package com.hspedu.poly_.objpoly_;

public class Dog extends Animal{
    public void cry(){
        System.out.println("Dog cry()小狗汪汪叫...");
    }
}

PolyObject.java

package com.hspedu.poly_.objpoly_;

public class PolyObject {
    public static void main(String[] args) {
        //体验对象多态的特点
        //animal编译类型就是Animal,运行类型就是Dog
        Animal animal = new Dog();
        //因为运行时,执行到该行时,animal运行类型就是Dog,所以cry就是dog cry
        animal.cry();//Dog cry()小狗汪汪叫...

        //animal编译类型是Animal,运行类型就是Cat
        animal = new Cat();
        animal.cry();//Cat cry()小猫喵喵叫...
    }
}

com.hspedu.poly_.Animal.java
package com.hspedu.poly_;

public class Animal {

    private String name;

    public Animal(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
com.hspedu.poly_.Cat.java
package com.hspedu.poly_;

public class Cat extends Animal {
    public Cat(String name) {
        super(name);
    }
}
com.hspedu.poly_.Dog.java
package com.hspedu.poly_;

public class Dog extends Animal {
    public Dog(String name) {
        super(name);
    }
}

com.hspedu.poly_.Pig.java

package com.hspedu.poly_;

public class Pig extends Animal {
    public Pig(String name) {
        super(name);
    }
}

com.hspedu.poly_.Rice.java

package com.hspedu.poly_;

public class Rice extends Food{
    public Rice(String name) {
        super(name);
    }
}
com.hspedu.poly_.Fish.java
package com.hspedu.poly_;

public class Fish extends Food {

    public Fish(String name) {
        super(name);
    }

}
com.hspedu.poly_.Bone.java
package com.hspedu.poly_;

public class Bone extends Food {

    public Bone(String name) {
        super(name);
    }
}
com.hspedu.poly_.Food.java
package com.hspedu.poly_;

public class Food {
    private String name;

    public Food(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
com.hspedu.poly_.Master.java
package com.hspedu.poly_;

public class Master {
    private String name;

    public Master(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    //使用多态机制 ,可以统一管理主人喂食的问题
    //animal编译类型是Animal,可以指向(接收)Animal子类的对象
    //food变异类型是Food,可以指向(接收)Food子类的对象
    public void feed(Animal animal,Food food){
        System.out.println("主人" + name + "给" + animal.getName() + "吃" + food.getName());
    }

//    //主人给小狗喂食,骨头
//    public void feed(Dog dog,Bone bone){
//        System.out.println("主人" + name + "给" + dog.getName() + "吃" + bone.getName());
//    }
//    public void feed(Cat cat,Fish fish){
//        System.out.println("主人" + name + "给" + cat.getName() + "吃" + fish.getName());
//    }
}
com.hspedu.poly_.poly01.java
package com.hspedu.poly_;

public class Poly01 {
    public static void main(String[] args) {
        Master tom = new Master("汤姆");
        Dog dog = new Dog("大黄~");
        Bone bone = new Bone("大棒骨~");
        tom.feed(dog,bone);
        System.out.println("==============");
        Cat cat = new Cat("小花猫~");
        Fish fish = new Fish("黄花鱼~");
        tom.feed(cat,fish);
        System.out.println("==============");
        //添加给小猪喂米饭
        Pig pig = new Pig("小白猪");
        Rice rice = new Rice("米饭");
        tom.feed(pig,rice);
        //输出结果为
        //主人汤姆给大黄~吃大棒骨~
        //==============
        //主人汤姆给小花猫~吃黄花鱼~
        //==============
        //主人汤姆给小白猪吃米饭
    }
}

Animal.java

package com.hspedu.poly_.detail_;

public class Animal {
    String name = "动物";
    int age = 10;
    public void sleep(){
        System.out.println("睡");
    }
    public void run(){
        System.out.println("跑");
    }
    public void eat(){
        System.out.println("吃");
    }
    private void show(){
        System.out.println("hello,你好");
    }

}

Cat.java

package com.hspedu.poly_.detail_;

public class Cat extends Animal{
    public void eat(){
        System.out.println("猫吃鱼");
    }
    public void catchMouse(){//Cat特有方法
        System.out.println("猫抓老鼠");
    }
}

Dog.java

package com.hspedu.poly_.detail_;

public class Dog extends Animal {
}

PolyDetail.java

package com.hspedu.poly_.detail_;

public class PolyDetail {
    public static void main(String[] args) {
        //向上转型:父类的引用指向了子类的对象
        //语法:父类类型引用名=new 子类类型();
        Animal animal = new Cat();
//        Object obj = new Cat();//Object也是Cat的父类的父类,可以使用
        System.out.println("ok~~");

        //向上转型方法的规则:
        //1.可以调用父类中的所有成员(需要遵守访问权限)
        //2.但是不能调用子类的特有的成员(属性和方法)
        //3.因为在编译阶段,能调用哪些成员,是由编译类型来决定的
        //animal.catchMouse();错误
        //4.最终运行效果看子类(运行类型)的具体实现,即调用方法时,按照从子类(运行类型)开始查找方法,然后调用,规则和我们前面讲的方法调用规则一致。
        animal.eat();//猫吃鱼
        animal.run();//跑
        //animal.show();//错误,private权限受阻
        animal.sleep();//睡

        
        //多态的向下转型:
        //调用Cat的catchMouse方法
        //1.语法:子类类型  引用名 = (子类类型) 父类引用
        //cat的编译类型Cat,运行类型是Cat
        Cat cat = (Cat) animal;
        cat.catchMouse();//猫抓老鼠
        //2.要求父类的引用必须指向的是当前目标类型的对象
        //Dog dog = (Dog) animal;//错误,类异常
    }
}

PolyDetail02.java

package com.hspedu.poly_.detail_;

public class PolyDetail02 {
    public static void main(String[] args) {
        //属性没有重写之说,属性的值看编译类型
        Base base = new Sub();//向上转型
        System.out.println(base.count);//10(直接看编译类型)
        Sub sub = new Sub();
        System.out.println(sub.count);//20
    }
}
class Base {
    int count = 10;
}
class Sub extends Base{
    int count = 20;
}

PolyDetail03.java

package com.hspedu.poly_.detail_;

public class PolyDetail03 {
    public static void main(String[] args) {
        BB bb = new BB();
        System.out.println(bb instanceof BB);//true
        System.out.println(bb instanceof AA);//true

        //aa的编译类型是AA,运行类型是BB
        AA aa = new BB();
        System.out.println(aa instanceof AA);//true
        System.out.println(aa instanceof BB);//true
        //结论:判断对象的运行类型是否为XX类型或者XX类型的子类型

        Object obj = new Object();
        System.out.println((obj instanceof AA));//false
        String str = "hello";
        //System.out.println(str instanceof AA);//没有任何关系
        System.out.println(str instanceof Object);//true

    }
}
class AA{

}
class BB extends AA{

}

PolyExercise01.java

package com.hspedu.poly_.exercise_;

public class PolyExercise01 {
    public static void main(String[] args) {
        double d = 13.4;//ok
        long l = (long)d;//ok
        System.out.println(l);//13
        int in = 5;//ok
        //boolean b = (boolean)in;错误,boolean->int
        Object obj = "hello";//ok,向上转型
        String objStr = (String)obj;//ok,向下转型
        System.out.println(objStr);//hello

        Object objPri =  new Integer(5);//ok,向上转型
        String str = (String)objPri;//错误class ClassCastException指向Integer的父类引用,转成String
        Integer sr1 = (Integer)objPri;//ok,向下转型
    }
}

PolyExercise02.java

package com.hspedu.poly_.exercise_;

public class PolyExercise02 {
    public static void main(String[] args) {
        Sub s = new Sub();
        System.out.println(s.count);//20
        s.display();//20
        Base b = s;
        System.out.println(b == s);//true
        System.out.println(b.count);//10
        b.display();//20
    }
}

class Base{
    int count = 10;
    public void display(){
        System.out.println(this.count);
    }
}
class Sub extends Base{
    int count = 20;
    public void display(){
        System.out.println(this.count);
    }
}

DynamicBinding.java

package com.hspedu.poly_.dynamic_;

public class DynamicBinding {
    public static void main(String[] args) {
        //a的编译类型A,运行类型B
        A a = new B();//向上转型
        System.out.println(a.sum());//30
        System.out.println(a.sum1());//20
    }
}
class A{
    public int i = 10;
    //动态绑定机制:
    //1.当调用对象方法的时候,该方法会和该对象的内存地址/运行类型绑定
    public int sum(){
        return getl() + 10;
    }
    //2.当调用对象属性时,没有动态绑定机制,哪里声明,哪里使用
    public int sum1(){
        return i + 10;
    }
    public int getl(){//父类getI
        return i;
    }
}
class B extends A{
    public int i = 20;
//    public int sum(){
//        return i + 20;
//    }
    public int getl(){//子类getI()
        return i;
    }
//    public int sum1(){
//        return i + 10;
//    }
}

Person.java

package com.hspedu.poly_.polyarr_;

public class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
    public String say(){
        return name + "\t" + age;
    }
}

Student.java

package com.hspedu.poly_.polyarr_;

public class Student extends Person{
    private double score;

    public Student(String name, int age, double score) {
        super(name, age);
        this.score = score;
    }

    public double getScore() {
        return score;
    }

    public void setScore(double score) {
        this.score = score;
    }

    //特有方法
    public void study(){
        System.out.println("学生" + getName() + "正在学java课程 ");
    }

    //重写父类的say()
    public String say() {
        return "学生" + super.say() + " score=" + score;
    }
}

Teacher.java

package com.hspedu.poly_.polyarr_;

public class Teacher extends Person{
    private double salary;

    public Teacher(String name, int age, double salary) {
        super(name, age);
        this.salary = salary;
    }

    public double getSalary() {
        return salary;
    }

    public void setSalary(double salary) {
        this.salary = salary;
    }

    //特有方法
    public void teach(){
        System.out.println("老师" + getName() + "正在讲java课程 ");
    }

    //重写父类的say()
    public String say() {
        return "老师" + super.say() + " salary=" + salary;
    }
}

PolyArray.java

package com.hspedu.poly_.polyarr_;

public class PolyArray {
    public static void main(String[] args) {
        //应用实例:现有一个继承结构如下:要求创建1个Peron对象
        //2个Student 对象和2个Teacher对象,统一放在数组中,并调用每个对象say()方法。
        Person[] persons = new Person[5];
        persons[0] = new Person("jack",20);
        persons[1] = new Student("mary",18,99.8);
        persons[2] = new Student("Smith",19,66.6);
        persons[3] = new Teacher("Scott",30,20000);
        persons[4] = new Teacher("King",50,25000);

        //循环遍历多态数组,调用say()方法
        for (int i = 0; i < persons.length; i++) {
            //persons[i]编译类型是Person,运行类型是根据实际情况由JVM来判断
            System.out.println(persons[i].say());//动态绑定机制
            //使用类型判断和向下转型
            if(persons[i] instanceof Student){//判断persons[i]的运行类型是不是Student
                Student student = (Student)persons[i];
                student.study();
                //((Student)persons[i]).study();
            }else if(persons[i] instanceof Teacher){
                Teacher teacher = (Teacher)persons[i];
                teacher.teach();
                //((Teacher)persons[i]).teach();
            }else if(persons[i] instanceof Person){

            }else{
                System.out.println("你的类型有误,请自己检查");
            }
        }

    }
}

Employee.java

package com.hspedu.poly_.polyparameter_;

public class Employee {
    private String name;
    private double salary;

    public Employee(String name, double salary) {
        this.name = name;
        this.salary = salary;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getSalary() {
        return salary;
    }

    public void setSalary(double salary) {
        this.salary = salary;
    }

    //得到年工资的方法
    public double getAnnual(){
        return 12 * salary;
    }
}

Worker.java

package com.hspedu.poly_.polyparameter_;

public class Worker extends Employee{
    public Worker(String name, double salary) {
        super(name, salary);
    }
    public void work(){
        System.out.println("普通员工" + getName() + " is working");
    }

    //重写获取年薪的方法
    public double getAnnual() {//因为普通员工没有其他收入,直接调用父类方法
        return super.getSalary();
    }
}

Manager.java

package com.hspedu.poly_.polyparameter_;

public class Manager extends Employee{
    private double bonus;

    public Manager(String name, double salary, double bonus) {
        super(name, salary);
        this.bonus = bonus;
    }

    public double getBonus() {
        return bonus;
    }

    public void setBonus(double bonus) {
        this.bonus = bonus;
    }
    public void manage(){
        System.out.println("经理" + getName() + " is managing");
    }

    //重写获取年薪的方法
    public double getAnnual() {
        return super.getAnnual() + bonus;
    }
}

PolyParameter.java

package com.hspedu.poly_.polyparameter_;

public class PolyParameter {
    public static void main(String[] args) {
        Worker tom = new Worker("tom", 2500);
        Manager milan = new Manager("milan", 5000, 200000);
        PolyParameter polyParameter = new PolyParameter();
        polyParameter.showEmpAnnual(tom);//2500.0
        polyParameter.showEmpAnnual(milan);//260000.0
        System.out.println("=======");
        polyParameter.testWork(tom);//普通员工tom is working
        polyParameter.testWork(milan);//经理milan is managing
    }
    //实现获取任何员工对象的年工资,并在main方法中调用该方法[e.getAnnual()]
    public void showEmpAnnual(Employee e){
        System.out.println(e.getAnnual());//动态绑定机制
    }
    //添加一个方法,testWork,如果是普通与昂,则调用work方法,如果是经理,则调用manage方法
    public void testWork(Employee e){
        if(e instanceof Worker){
            ((Worker) e).work();
        }else if(e instanceof Manager){
            ((Manager) e).manage();
        }else{
            System.out.println("不做处理");
        }
    }
}

Equals01.java

package com.hspedu.object_;

public class Equals01 {
    public static void main(String[] args) {
        A a = new A();
        A b = a;
        A c = b;
        System.out.println(a == c);//true
        System.out.println(b == c);//true
        B bObj = a;
        System.out.println(bObj == c);//true
    }
}
class A extends B{

}
class B{

}

Equals01.java

package com.hspedu.object_;

public class Equals01 {
    public static void main(String[] args) {
        A a = new A();
        A b = a;
        A c = b;
        System.out.println(a == c);//true
        System.out.println(b == c);//true
        B bObj = a;
        System.out.println(bObj == c);//true
        int num1 = 10;
        double num2 = 10.0;
        System.out.println(num1 == num2);//true

        //equals方法,源码怎么查看
        //把光标放在equals上,直接输入ctrl+b

        //1.JDK源码String 类的equals方法
        /*
        //把Object的equals方法重写了,变成了比较两个字符串值是否相同
        public boolean equals(Object anObject) {
        if (this == anObject) {//如果是同一个对象
            return true;//返回true
        }
        if (anObject instanceof String) {//判断类型
            String anotherString = (String)anObject;//向下转型
            int n = value.length;
            if (n == anotherString.value.length) {//如果长度相同
                char v1[] = value;
                char v2[] = anotherString.value;
                int i = 0;
                while (n-- != 0) {//然后一个个比较字符
                    if (v1[i] != v2[i])
                        return false;
                    i++;
                }
                return true;
            }
        }
        return false;//如果比较的不是字符串,直接返回false
    }*/
        String str1 = new String("hspedu");
        String str2 = new String("hspedu");
        System.out.println(str1 == str2);//false
        System.out.println(str1.equals(str2));//true

        //2.JDK源码Object类的equals方法
        /*
        //即Object的equals方法默认就是比较对象地址是否相同
        //也就是判断两个对象是不是同一个对象
        public boolean equals(Object obj) {
        return (this == obj);
        }

        */

        //3.JDK源码Integer类的equals方法
        //也重写的Object的equals方法,变成了判断两个值是否相同
        /*
        public boolean equals(Object obj) {
            if (obj instanceof Integer) {
                return value == ((Integer)obj).intValue();
            }
            return false;
         }
        * */
        Integer integer1 = new Integer(1000);
        Integer integer2 = new Integer(1000);
        System.out.println(integer1 == integer2);//false
        System.out.println(integer1.equals(integer2));//true
    }
}
class A extends B{

}
class B{

}

EqualsExercise01.java

package com.hspedu.object_;

public class EqualsExercise01 {
    public static void main(String[] args) {
        Person person1 = new Person("jack", 10, '男');
        Person person2 = new Person("jack", 10, '男');

        System.out.println(person1.equals(person2));//假,因为没有重写,只比较person1和person2是否是同一个对象,重写之后,比较两个Person对象的各个属性值,返回true
    }
}
//判断两个Person对象的内容是否相等,如果两个Person对象的各个属性值都一样,则返回true,反之false
class Person{//extends Object
    private String name;
    private int age;
    private char gender;

    //重写Object的equals方法
    public boolean equals(Object obj) {
        //判断如果比较的两个对象是同一个对象则直接返回true
        if(this == obj){
            return true;
        }
        //类型判断
        if(obj instanceof Person){

            //类型转换,向下转型,因为需要得到obj的各个属性
            Person p = (Person)obj;
            return this.name.equals(p.name) && this.age == p.age && this.gender == p.gender;
        }
        //如果类型不是Person,则直接返回false
        return false;
    }

    public Person(String name, int age, char gender) {
        this.name = name;
        this.age = age;
        this.gender = gender;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public char getGender() {
        return gender;
    }

    public void setGender(char gender) {
        this.gender = gender;
    }
}

HashCode.java

package com.hspedu.object_;

public class HashCode {
    public static void main(String[] args) {
        AA aa1 = new AA();
        AA aa2 = new AA();
        AA aa3 = aa1;
        System.out.println("aa1.hashCode=" + aa1.hashCode());
        System.out.println("aa2.hashCode=" +aa2.hashCode());
        System.out.println("aa3.hashCode=" +aa3.hashCode());
    }
}

class AA{

}

ToString.java

package com.hspedu.object_;

public class ToString {
    public static void main(String[] args) {
        //Object的 toString()源码
        //1.getClass().getName()类的全类名(包名+类名)
        //2.Interger.toHexString(HashCode())将对象的hashCode值转成16进制字符串
//        public String toString() {
//            return getClass().getName() + "@" + Integer.toHexString(hashCode());
//        }
        Monster monster = new Monster("小妖怪", "巡山", 1000);
        System.out.println(monster.toString() + " hachCode=" + monster.hashCode());
        //com.hspedu.object_.Monster@1540e19d hachCode=356573597
        //如下重写toString方法,输出结果为:Monster{name='小妖怪', job='巡山', salary=1000.0} hachCode=356573597
        //当直接输出一个对象时,toString方法会被默认调用
        System.out.println(monster);//Monster{name='小妖怪', job='巡山', salary=1000.0}
    }

}
class Monster{
    private String name;
    private String job;
    private double salary;

    public Monster(String name, String job, double salary) {
        this.name = name;
        this.job = job;
        this.salary = salary;
    }
    //重写toString方法,输出对象的属性

    @Override
    public String toString() {//重写后,一般是把对象的属性输出,也可以自己定制
        return "Monster{" +
                "name='" + name + '\'' +
                ", job='" + job + '\'' +
                ", salary=" + salary +
                '}';
    }
}

Finalize.java

package com.hspedu.object_;

//演示 Finalize的用法
public class Finalize {
    public static void main(String[] args) {
        Car bmw = new Car("宝马");
        bmw = null;//这时Car对象就是一个垃圾,垃圾回收器就会回收(销毁)对象,在销毁对象前,会调用该对象的Finalize方法,可以在finalize中,写业务逻辑代码(比如释放资源:数据库连接,或者打开的文件...),吐过不重写finalize,那么就会调用Object类的finalize,即默认处理,如果重写了finalize,就可以实现自己的逻辑
        //bmw.finalize();
        System.gc();//主动调用垃圾回收器
        System.out.println("程序退出了...");
    }
}

class Car{
    private String name;

    public Car(String name) {
        this.name = name;
    }
    //重写finalize

    @Override
    protected void finalize() throws Throwable {
        System.out.println("我们销毁汽车" + name);
        System.out.println("释放了某些资源...");
    }
}

Debug01.java

package com.hspedu.debug_;

public class Debug01 {
    public static void main(String[] args) {
        //演示逐行执行代码
        int sum = 0;
        for(int i = 0;i < 5;i++){
            sum += i;
            System.out.println("i=" + i);
            System.out.println("sum=" + i);

        }
        System.out.println("退出for...");
    }
}

Debug02.java

package com.hspedu.debug_;

public class Debug02 {
    public static void main(String[] args) {
        int[] arr = {1,10,-1};
        for(int i = 0;i < arr.length;i++){
            System.out.println(arr[i]);
        }
        System.out.println("退出 for...");
    }
}

Debug03.java

package com.hspedu.debug_;

import java.util.Arrays;

public class Debug03 {
    public static void main(String[] args) {
        //debug源码
        int[] arr = {8,-1,199,70,10};
        //程序,追入sort的源码,Arrays.sort方法底层实现debug
        Arrays.sort(arr);
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + "\t");
        }
    }
}

Debug04.java

package com.hspedu.debug_;

import java.util.Arrays;
//演示执行到下一个断点,同时支持动态的下断点
public class Debug04 {
    public static void main(String[] args) {
        //debug源码
        int[] arr = {8,-1,199,70,10};
        //程序,追入sort的源码,Arrays.sort方法底层实现debug
        Arrays.sort(arr);
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + "\t");
        }
        System.out.println();
        System.out.println("hello100");
        System.out.println("hello200");
        System.out.println("hello300");
        System.out.println("hello400");
        System.out.println("hello500");
        System.out.println("hello600");
        System.out.println("hello700");
    }
}

DebugExercise.java

package com.hspedu.debug_;

//演示debug对象创建的过程,加深对调试的理解
public class DebugExercise {
    public static void main(String[] args) {
        //创建对象的流程
        //1.加载Person信息
        //2.初始化->默认初始化->显示初始化->构造器初始化
        //3.返回对象的地址
        Person jack = new Person("jack", 20);
        System.out.println(jack);
    }
}
class Person{
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

DebugExercise.java

package com.hspedu.Debud_;

public class DebugExercise {
    public static void main(String[] args) {
        //a的编译类型A,运行类型B
        A a = new B();//向上转型
        System.out.println(a.sum());//30
        System.out.println(a.sum1());//20
    }
}
class A{
    public int i = 10;
    //动态绑定机制:
    //1.当调用对象方法的时候,该方法会和该对象的内存地址/运行类型绑定
    public int sum(){
        return getl() + 10;
    }
    //2.当调用对象属性时,没有动态绑定机制,哪里声明,哪里使用
    public int sum1(){
        return i + 10;
    }
    public int getl(){//父类getI
        return i;
    }
}
class B extends A{
    public int i = 20;
//    public int sum(){
//        return i + 20;
//    }
    public int getl(){//子类getI()
        return i;
    }
//    public int sum1(){
//        return i + 10;
//    }
}

SmallChangeAys.java(面向过程版本)

package com.hspedu.smallchange;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
import java.util.logging.SimpleFormatter;

public class SmallChangeAys {
    //化繁为简
    //1.先完成显示菜单,并可以选择菜单,给出对应提示
    //2.完成零钱通明细
    //3.完成收益入账
    //4.消费
    //5.退出
    //6.用户输入4退出时,给出提示“你确定要退出吗?y/n”,必须输入正确的y/n,否则循环输入指令,直到输入y或n
    //7.在收益入账和消费时,判断金额是否合理,并给出相应的提示
    public static void main(String[] args) {
        //定义相关的变量
        boolean loop = true;
        Scanner scanner = new Scanner(System.in);
        String key = "";

        //2.完成零钱通明细
        //解决方法有三种:
        //(1)可以把收益入账和消费,保存到数组
        //(2)可以使用对象
        //(3)简单的话可以使用String拼接
        String detail = "---------------零钱通明细------------------";

        //3.完成收益入账
        //定义新的变量(完成功能驱动程序猿增加新的变化和代码)
        double money = 0;
        double balance = 0;
        Date date = null;//date是java.util.Date类型,表示日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");//可以用于日期格式化的对象

        //4.消费
        //定义新变量,保存消费的原因
        String note = "";
        do{
            System.out.println("\n=======零钱通菜单=======");
            System.out.println("\t\t\t\t1 零钱通明细");
            System.out.println("\t\t\t\t2 收益入账");
            System.out.println("\t\t\t\t3 消费");
            System.out.println("\t\t\t\t4 退    出");

            System.out.print("请选择(1-4):");
            key = scanner.next();
            //使用switch分支
            switch(key){
                case "1" :
                    System.out.println(detail);
                    break;
                case "2" :
                    System.out.print("收益入账金额:");
                    money = scanner.nextDouble();
                    //money的范围应该校验
                    //7.在收益入账时,判断金额是否合理,并给出相应的提示
                    //思路:找出不正确的金额条件,给出提示,直接break
                    if(money <= 0){
                        System.out.println("收益入账金额需要大于0");
                        break;
                    }
                    balance += money;
                    //拼接收益入账信息到detail
                    date = new Date();//获取当前日期
                    detail += "\n收益入账\t+" + money + "\t" + sdf.format(date) + "\t" + balance;
                    break;
                case "3" :
                    System.out.print("消费金额:");
                    money = scanner.nextDouble();
                    //money的范围应该校验
                    //7.在消费时,判断金额是否合理,并给出相应的提示
                    //思路:找出不正确的金额条件,给出提示,直接break
                    //过关斩将校验法
                    if(money <= 0 || money > balance){
                        System.out.println("您的消费金额应该在 0 ~ " + balance);
                        break;
                    }
                    System.out.print("消费说明:");
                    note = scanner.next();
                    balance -= money;
                    //拼接消费信息到detail
                    date = new Date();//获取当前日期
                    detail += "\n" + note + "\t-" + money + "\t" + sdf.format(date) + "\t" + balance;
                    break;
                case "4" :
                    //5.退出
                    //6.用户输入4退出时,给出提示“你确定要退出吗?y/n”,必须输入正确的y/n,否则循环输入指令,直到输入y或n
                    //(1)定义一个变量choice,接收用户的输入
                    //(2)使用while+break,来处理接收到的输入是y或者n
                    //(3)退出while后,判断choice是y还是n,就可以决定是否退出
                    //(4)一般代码完成一个小功能,尽量不要混在一起
                    String choice = "";
                    while(true){//要求用户必须输入y/n,否则就一直循坏
                        System.out.println("你确定要退出吗?y/n");
                        choice = scanner.next();
                        if("y".equals(choice) || "n".equals(choice)){
                            break;
                        }
                        /*
                        * if("y".equal(choice)){
                        *      loop = false;
                        *       break;
                        * }else if("n".equals(choice)){
                        *       break;
                        * }
                        */
                    }
                    //当用户退出while,进行判断
                    if(choice.equals("y")){
                        loop = false;
                    }
                    break;
                default:
                    System.out.println("选择有误,请重新选择");
            }

        }while(loop);

        System.out.println("------退出了零钱通项目-------");
    }
}

SmallChangeAysOOP.java(面向对象版本)

package com.hspedu.smallchange.oop;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;

/*
* 该类是完成零钱通的各个功能的类
* 使用OOP(面向对象编程)
* 将各个功能对应一个方法
* */
public class SmallChangeSysOOP {
    //1.定义相关的变量
    boolean loop = true;
    Scanner scanner = new Scanner(System.in);
    String key = "";

    //2.完成零钱通明细
    //解决方法有三种:
    //(1)可以把收益入账和消费,保存到数组
    //(2)可以使用对象
    //(3)简单的话可以使用String拼接
    String detail = "---------------零钱通明细------------------";

    //3.完成收益入账
    //定义新的变量(完成功能驱动程序猿增加新的变化和代码)
    double money = 0;
    double balance = 0;
    Date date = null;//date是java.util.Date类型,表示日期
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");//可以用于日期格式化的对象

    //4.消费
    //定义新变量,保存消费的原因
    String note = "";
    //1.先完成显示菜单,并可以选择
    public void mainMenu(){
        do{
            System.out.println("\n=======OOP零钱通菜单=======");
            System.out.println("\t\t\t\t1 零钱通明细");
            System.out.println("\t\t\t\t2 收益入账");
            System.out.println("\t\t\t\t3 消费");
            System.out.println("\t\t\t\t4 退    出");

            System.out.print("请选择(1-4):");
            key = scanner.next();
            //使用switch分支
            switch(key){
                case "1" :
                    this.detail();
                    break;
                case "2" :
                    this.income();
                    break;
                case "3" :
                    this.pay();
                    break;
                case "4" :
                    this.exit();
                    break;
                default:
                    System.out.println("选择有误,请重新选择");
            }

        }while(loop);
    }
    //2.完成零钱通明细
    public void detail(){
        System.out.println(detail);
    }
    //3.完成收益入账
    public void income(){
        System.out.print("收益入账金额:");
        money = scanner.nextDouble();
        //money的范围应该校验
        //7.在收益入账时,判断金额是否合理,并给出相应的提示
        //思路:找出不正确的金额条件,给出提示,直接return
        if(money <= 0){
            System.out.println("收益入账金额需要大于0");
            return;//退出方法不再执行后面的代码。
        }
        balance += money;
        //拼接收益入账信息到detail
        date = new Date();//获取当前日期
        detail += "\n收益入账\t+" + money + "\t" + sdf.format(date) + "\t" + balance;
    }
    //4.完成消费
    public void pay(){
        System.out.print("消费金额:");
        money = scanner.nextDouble();
        //money的范围应该校验
        //7.在消费时,判断金额是否合理,并给出相应的提示
        //思路:找出不正确的金额条件,给出提示,直接return
        //过关斩将校验法
        if(money <= 0 || money > balance){
            System.out.println("您的消费金额应该在 0 ~ " + balance);
            return;
        }
        System.out.print("消费说明:");
        note = scanner.next();
        balance -= money;
        //拼接消费信息到detail
        date = new Date();//获取当前日期
        detail += "\n" + note + "\t-" + money + "\t" + sdf.format(date) + "\t" + balance;
    }
    //5.退出
    public void exit(){
        //5.退出
        //6.用户输入4退出时,给出提示“你确定要退出吗?y/n”,必须输入正确的y/n,否则循环输入指令,直到输入y或n
        //(1)定义一个变量choice,接收用户的输入
        //(2)使用while+break,来处理接收到的输入是y或者n
        //(3)退出while后,判断choice是y还是n,就可以决定是否退出
        //(4)一般代码完成一个小功能,尽量不要混在一起
        String choice = "";
        while(true){//要求用户必须输入y/n,否则就一直循坏
            System.out.println("你确定要退出吗?y/n");
            choice = scanner.next();
            if("y".equals(choice) || "n".equals(choice)){
                break;
            }
            /*
             * if("y".equal(choice)){
             *      loop = false;
             *       break;
             * }else if("n".equals(choice)){
             *       break;
             * }
             */
        }
        //当用户退出while,进行判断
        if(choice.equals("y")){
            loop = false;
        }
    }
}

SmallChangeSysApp.java

package com.hspedu.smallchange.oop;

/*
* 这里直接调用SmallChangeSysOOP 对象,显示主菜单即可
* */
public class SmallChangeSysApp {
    public static void main(String[] args) {
        new SmallChangeSysOOP().mainMenu();
    }
}

Person.java

package com.hspedu.homework.homework01;

public class Person {
    private String name;
    private int age;
    private String job;

    public Person(String name, int age, String job) {
        this.name = name;
        this.age = age;
        this.job = job;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getJob() {
        return job;
    }

    public void setJob(String job) {
        this.job = job;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", job='" + job + '\'' +
                '}';
    }
}


Homework01.java

package com.hspedu.homework.homework01;


public class Homework01 {
    public static void main(String[] args) {
        Person[] persons = new Person[3];
        persons[0] = new Person("jack", 18, "docter");
        persons[1] = new Person("tom", 33, "sporter");
        persons[2] = new Person("mary", 25, "tercher");

        //输出当前对象的对象数组
        for(int i = 0;i < persons.length;i++){
            System.out.println(persons[i]);
        }

        //冒泡排序
        Person tmp = null;
        for(int i = 0;i < persons.length - 1;i++){//外层循环
            for(int j = 0;j < persons.length -1 -i;j++){//内层循环
                //1.并按照age从大到小进行排序,如果前面的age小于后面就交换
                //2.并按照age从小到大进行排序,如果前面的age小于后面就交换(if条件里的<更改为>即可)
                //3.要求按照名字的长度从小到大排序,比较条件为persons[i].getName().length() > persons[i+1].getName().length()
                if(persons[j].getAge() < persons[j+1].getAge()){
                    tmp = persons[j];
                    persons[j] = persons[j+1];
                    persons[j+1] = tmp;
                }
            }
        }
        System.out.println("===============");
        //输出排序后对象的对象数组
        for(int i = 0;i < persons.length;i++){
            System.out.println(persons[i]);
        }
    }
}

homework.java

package com.hspedu.homework.homework03;

public class Homework03 {
    public static void main(String[] args) {
        Teacher Professor = new Professor("mary",22,"教授",5100.0,1.3);
        Professor.introduce();
    }
}

Teacher.java

package com.hspedu.homework.homework03;

public class Teacher {
    private String name;
    private int age;
    private String post;
    private double salary;
    //增加一个工资级别
    private double grade;

    public Teacher(String name, int age, String post, double salary, double grade) {
        this.name = name;
        this.age = age;
        this.post = post;
        this.salary = salary;
        this.grade = grade;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getPost() {
        return post;
    }

    public void setPost(String post) {
        this.post = post;
    }

    public double getSalary() {
        return salary;
    }

    public void setSalary(double salary) {
        this.salary = salary;
    }

    public double getGrade() {
        return grade;
    }

    public void setGrade(double grade) {
        this.grade = grade;
    }

    public void introduce(){
        System.out.println("老师姓名是" + name + ",年龄" +  age + ",职称" + post + ",工资是" +  salary * grade);
    }
}

Professor.java

package com.hspedu.homework.homework03;

public class Professor extends Teacher{
    public Professor(String name, int age, String post, double salary, double grade) {
        super(name, age, post, salary, grade);
    }
    public void introduce(){
        System.out.println("这是教授的信息");
        super.introduce();
    }
}

AssProfess.java

package com.hspedu.homework.homework03;

public class AssProfessor extends Teacher{

    public AssProfessor(String name, int age, String post, double salary, double grade) {
        super(name, age, post, salary, grade);
    }

    public void introduce(){
        System.out.println("这是副教授的信息");
        super.introduce();
    }
}

Lecturer.java

package com.hspedu.homework.homework03;

public class Lecturer extends Teacher{
    public Lecturer(String name, int age, String post, double salary, double grade) {
        super(name, age, post, salary, grade);
    }

    public void introduce(){
        System.out.println("这是讲师的信息");
        super.introduce();
    }
}

Worker.java

package com.hspedu.homework.homework04;

public class Worker {
    private String name;
    private double salary;
    private int days;
    private double grade;

    public Worker(String name, double salary, int days, double grade) {
        this.name = name;
        this.salary = salary;
        this.days = days;
        this.grade = grade;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getSalary() {
        return salary;
    }

    public void setSalary(double salary) {
        this.salary = salary;
    }

    public int getDays() {
        return days;
    }

    public void setDays(int days) {
        this.days = days;
    }

    public double getGrade() {
        return grade;
    }

    public void setGrade(double grade) {
        this.grade = grade;
    }

    public void getSal(){
        System.out.println("姓名" + name + ",工资=" + salary * days *grade);
    }
}

Genworker.java

package com.hspedu.homework.homework04;

public class GenWorker extends Worker{
    public GenWorker(String name, double salary, int days, double grade) {
        super(name, salary, days, grade);
    }
    //重写父类的getSal方法
    public void getSal(){
        //因为经理的计算方式和worker一样,所以直接调用父类
        System.out.print("普通员工");
        super.getSal();
    }
}

Manager.java

package com.hspedu.homework.homework04;

public class Manager extends Worker{
    //特有属性:奖金
    private double bonus;
    //创建Manager对象时,奖金是多少并不是确定的,因此在构造器中,不给bonus
    public Manager(String name, double salary, int days, double grade) {
        super(name, salary, days, grade);
    }

    public double getBonus() {
        return bonus;
    }

    public void setBonus(double bonus) {
        this.bonus = bonus;
    }

    //重写父类的getSal方法
    public void getSal(){
        //因为经理的计算方式和worker不一样,所以重写
        System.out.println("经理" + getName() + ",工资=" + (bonus + getDays() * getSalary() * getGrade()));
    }
}

Homework04.java

package com.hspedu.homework.homework04;

public class Homework04 {
    public static void main(String[] args) {
        Manager jack = new Manager("jack", 100, 20, 1.2);
        //设置奖金
        jack.setBonus(3000);
        jack.getSal();
        GenWorker daben = new GenWorker("daben", 50, 30, 1.0);
        daben.getSal();
    }
}

Employee.java

package com.hspedu.homework.homework05;

public class Employee {
    //属性
    //分析有一个带薪对的月份13,15,12
    private String name;
    private double salary;
    private int salMonth = 12;

    public Employee(String name, double salary) {
        this.name = name;
        this.salary = salary;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getSalary() {
        return salary;
    }

    public void setSalary(double salary) {
        this.salary = salary;
    }

    public int getSalMonth() {
        return salMonth;
    }

    public void setSalMonth(int salMonth) {
        this.salMonth = salMonth;
    }

    //方法
    //打印全年工资
    public void printSal(){
        System.out.println(name + "年工资=" + (salary * salMonth));
    }
}

Worker.java

package com.hspedu.homework.homework05;

public class Worker extends Employee{
    public Worker(String name, double salary) {
        super(name, salary);
    }

    public void printSal(){
        System.out.print("工人:");
        super.printSal();//使用了父类的printSal方法
    }
}

Peasant.java

package com.hspedu.homework.homework05;

public class Peasant extends Employee{
    public Peasant(String name, double salary) {
        super(name, salary);
    }

    public void printSal(){
        System.out.print("农民:");
        super.printSal();
    }
}

Waiter.java

package com.hspedu.homework.homework05;

public class Waiter extends Employee{
    public Waiter(String name, double salary) {
        super(name, salary);
    }

    public void printSal(){
        System.out.print("服务员:");
        super.printSal();
    }
}

Teacher.java

package com.hspedu.homework.homework05;

public class Teacher extends Employee{
    private double ClassSal;
    private int days;

    public Teacher(String name, double salary) {
        super(name, salary);
    }

    public double getClassSal() {
        return ClassSal;
    }

    public void setClassSal(double classSal) {
        ClassSal = classSal;
    }

    public int getDays() {
        return days;
    }

    public void setDays(int days) {
        this.days = days;
    }

    public void printSal(){
        System.out.print("老师:");
        System.out.println(getName() + "工资=" + (getSalary() * getSalMonth() + ClassSal * days));
    }
}

Scientist.java

package com.hspedu.homework.homework05;

public class Scientist extends Employee{
    private double bone;

    public Scientist(String name, double salary) {
        super(name, salary);
    }

    public double getBone() {
        return bone;
    }

    public void setBone(double bone) {
        this.bone = bone;
    }

    public void printSal(){
        System.out.print("科学家:");
        System.out.println(getName() + "工资=" + (getSalary() * getSalMonth() + bone));
    }
}

Homework05.java

package com.hspedu.homework.homework05;

public class Homework05 {
    public static void main(String[] args) {
        //农民:
        Peasant peasant = new Peasant("马杰克", 3000);
        peasant.setSalMonth(10);
        peasant.printSal();
        //服务员:
        Waiter waiter = new Waiter("其可", 6000);
        waiter.printSal();
        //工人:
        Worker worker = new Worker("刘昊然", 9000);
        worker.printSal();
        //IT老师:
        Teacher teacher = new Teacher("郭勇", 75000);
        teacher.setDays(360);
        teacher.setClassSal(1000);
        teacher.printSal();
        //科学家:
        Scientist scientist = new Scientist("邓佳佳", 30000);
        scientist.setBone(2000000);
        scientist.printSal();
    }
}

package com.hspedu.homework.homework07;

public class Homework07 {
}
class Test{
    String name = "Rose";
    Test(){
        System.out.println("Test");
    }
    Test(String name){
        this.name = name;//把父类的name=Rose修改name=john
    }
}

class Demo extends Test{
    String name = "Jack";
    Demo(){
        super();
        System.out.println("Demo");
    }
    Demo(String s){
        super(s);
    }
    public void test(){
        System.out.println(super.name);
        System.out.println(this.name);
    }
    public static void main (String[] args){
        new Demo().test();//匿名对象
        new Demo("john").test();//匿名对象
    }
/*
Test
Demo
Rose
Jack
john
Jack
* */

}

BankAccount.java

package com.hspedu.homework.homework08;

class BankAccount {
    private double balance;

    public BankAccount(double initialBalance) {
        this.balance = initialBalance;
    }

    //存款
    public void deposit(double amount) {
        balance += amount;
    }

    //取款
    public void withdraw(double amount) {
        balance -= amount;
    }

    public double getBalance() {
        return balance;
    }

    public void setBalance(double balance) {
        this.balance = balance;
    }
}

SavingsAccount.java

package com.hspedu.homework.homework08;

public class SavingsAccount extends BankAccount{

    //扩展前一个练习的BankAccount类
    //新类SavingsAccount每个月都有利息产生(earnMonthlyInterest方法被调用)
    //并且有每月三次免手续费的存款或者取款。在earnMonthlyInterest方法中重置交易计数
    //新增加属性
    private int count = 3;
    private double rate = 0.01;//利率

    public void earnMonthlyInterest(){//每个月初,统计上个月的利息,同时将count = 3
        count = 3;
        super.deposit(getBalance() * rate);
    }

    public SavingsAccount(double initialBalance) {
        super(initialBalance);
    }

    public int getCount() {
        return count;
    }

    public void setCount(int count) {
        this.count = count;
    }

    public double getRate() {
        return rate;
    }

    public void setRate(double rate) {
        this.rate = rate;
    }

    @Override
    public void deposit(double amount) {
        //判断是否还可以免手续费
        if(count > 0){
            super.deposit(amount);
        }else{
            super.deposit(amount - 1);
        }
        count--;//减去一次
    }

    @Override
    public void withdraw(double amount) {
        if(count > 0){
            super.withdraw(amount);
        }else{
            super.withdraw(amount + 1);
        }
        count--;
    }
}

CheckingAccount.java

package com.hspedu.homework.homework08;

public class CheckingAccount extends BankAccount{
    public CheckingAccount(double initialBalance) {
        super(initialBalance);
    }

    @Override
    public void deposit(double amount) {//存款
        super.deposit(amount - 1);//巧妙使用父类的deposit
        //1块钱转入银行的账号
    }

    @Override
    public void withdraw(double amount) {//存款
        super.withdraw(amount + 1);
        //1块钱转入银行的账号
    }
}

Homework08.java

package com.hspedu.homework.homework08;

public class Homework08 {
    public static void main(String[] args) {
//        CheckingAccount checkingAccount = new CheckingAccount(1000);
//        checkingAccount.deposit(10);
//        System.out.println(checkingAccount.getBalance());//1009.0
//        checkingAccount.withdraw(9);
//        System.out.println(checkingAccount.getBalance());//999.0

        //测试SavingAccount
        SavingsAccount savingsAccount = new SavingsAccount(1000);
        savingsAccount.deposit(100);//免手续费
        savingsAccount.deposit(100);//免手续费
        savingsAccount.deposit(100);//免手续费
        System.out.println(savingsAccount.getBalance());//1300.0
        savingsAccount.deposit(100);
        System.out.println(savingsAccount.getBalance());//1399.0

        //月初,定时器自动调用一下 earnMonthlyInterest
        savingsAccount.earnMonthlyInterest();
        System.out.println(savingsAccount.getBalance());//1399+13.99=1412.99
        savingsAccount.withdraw(100);//免手续费
        System.out.println(savingsAccount.getBalance());//1412.99-100=1312.99
        savingsAccount.withdraw(100);//免手续费
        savingsAccount.withdraw(100);//免手续费
        System.out.println(savingsAccount.getBalance());//1412.99-200=1112.99
        savingsAccount.deposit(100);//扣手续费
        System.out.println(savingsAccount.getBalance());//1112.99+100-1=1211.99
    }
}

Homework09.java

package com.hspedu.homework;

public class Homework09 {
    public static void main(String[] args) {
        LabelPoint haha = new LabelPoint("haha", 232, 323.3);
    }
}
class Point{
    private double x;
    private double y;

    public Point(double x, double y) {
        this.x = x;
        this.y = y;
    }
}

class LabelPoint extends Point{
    private String label;

    public LabelPoint(String label,double x, double y) {
        super(x, y);
        this.label = label;
    }
}

Homework10.java

package com.hspedu.homework.homework10;

public class Homework10 {
    public static void main(String[] args) {
        Doctor doctor1 = new Doctor("jack", 20, "牙科医生", '男', 20000);
        Doctor doctor2 = new Doctor("jack", 22, "牙科医生", '男', 20000);
        System.out.println(doctor1.equals(doctor2));
    }
}

Doctor.java

package com.hspedu.homework.homework10;

public class Doctor {
    private String name;
    private int age;
    private String job;
    private char gender;
    private double sal;

    public Doctor(String name, int age, String job, char gender, double sal) {
        this.name = name;
        this.age = age;
        this.job = job;
        this.gender = gender;
        this.sal = sal;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getJob() {
        return job;
    }

    public void setJob(String job) {
        this.job = job;
    }

    public char getGender() {
        return gender;
    }

    public void setGender(char gender) {
        this.gender = gender;
    }

    public double getSal() {
        return sal;
    }

    public void setSal(double sal) {
        this.sal = sal;
    }
    public boolean equals(Object obj){
        //判断两个比较对象是否相同
        if(this == obj){
            return true;
        }
        //判断object是否是Doctor类型或者是其子类
        if(!(obj instanceof Doctor)){
            return false;
        }
        //向下转型,因为obj的运行类型是Doctor或者其子类型
        Doctor doctor = (Doctor)obj;
        return this.name.equals(doctor.name) && this.age == doctor.age && this.gender == doctor.gender && this.job.equals(doctor.job) && this.sal == doctor.sal;
    }
}

Person.java

package com.hspedu.homework.homework13;

public class Person {
    private String name;
    private int age;
    private char sex;

    public Person(String name, int age, char sex) {
        this.name = name;
        this.age = age;
        this.sex = sex;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public char getSex() {
        return sex;
    }

    public void setSex(char sex) {
        this.sex = sex;
    }

    public String play(){
        return name + "爱玩";
    }

    public String basic() {
        return "姓名:" + name + "\n年龄:" + age + "\n性别:" + sex;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", sex=" + sex +
                '}';
    }
}

Teacher.java

package com.hspedu.homework.homework13;

import java.sql.SQLOutput;

public class Teacher extends Person{
    private int work_age;

    public Teacher(String name, int age, char sex, int work_age) {
        super(name, age, sex);
        this.work_age = work_age;
    }

    public int getWork_age() {
        return work_age;
    }

    public void setWork_age(int work_age) {
        this.work_age = work_age;
    }

    public void teach(){
        System.out.println(getName() + "承诺,我会认真教学。");
    }

    @Override
    public String play() {
        return super.play() + "象棋";
    }

    public void printInfo() {
        System.out.println("老师的信息如下:");
        System.out.println(super.basic());
        System.out.println("工龄:" + work_age);
        teach();
        System.out.println(play());
    }

    @Override
    public String toString() {
        return "Teacher{" +
                "work_age=" + work_age +
                '}' + super.toString();
    }
}

Student.java

package com.hspedu.homework.homework13;

public class Student extends Person{
    private String stu_id;

    public Student(String name, int age, char sex, String stu_id) {
        super(name, age, sex);
        this.stu_id = stu_id;
    }
    public void study(){
        System.out.println(getName() + "承诺,我会好好学习。");
    }

    public String getStu_id() {
        return stu_id;
    }

    public void setStu_id(String stu_id) {
        this.stu_id = stu_id;
    }

    @Override
    public String play() {
        return super.play() + "足球";
    }

    public void printInfo() {
        System.out.println("学生的信息如下:");
        System.out.println(super.basic());
        System.out.println("学号:" + getStu_id());
        study();
        System.out.println(play());
    }

    @Override
    public String toString() {
        return "Student{" +
                "stu_id='" + stu_id + '\'' +
                '}' + super.toString();
    }
}

Homework13.java

package com.hspedu.homework.homework13;

public class Homework13 {
    public static void main(String[] args) {
//        Teacher teacher = new Teacher("张飞",30,'男',5);
//        teacher.printInfo();
//        Student student = new Student("小明", 15, '男', "00023102");
//        System.out.println("----------");
//        student.printInfo();

        //定义多态数组,里面保存2个学生和2个教师,要求按照年龄从高到低排序
        Person[] persons = new Person[4];
        persons[0] = new Student("小明",10,'男',"00023102");
        persons[1] = new Student("小钱",20,'女',"00023881");
        persons[2] = new Teacher("老孙",36,'男',10);
        persons[3] = new Teacher("老李",26,'女',18);
        //创建对象
        Homework13 homework13 = new Homework13();
        homework13.bubbleSort(persons);

        //输出排序后的数组
        System.out.println("------排序后的数组---------");
        for (int i = 0; i < persons.length; i++) {
            System.out.println(persons[i]);
        }

        //遍历数组调用test方法
        System.out.println("===============");
        for (int i = 0; i < persons.length; i++) {
            homework13.test(persons[i]);
        }

    }
    //方法排序后的数组
    public void bubbleSort(Person[] persons){
        Person tmp = null;
        for(int i = 0;i < persons.length - 1;i++){
            for(int j = 0;j < persons.length - 1 - i ;j++){
                //判断条件,注意这里的条件可以根据需要变化
                if(persons[j].getAge() < persons[j+1].getAge()){
                    tmp = persons[j];
                    persons[j] = persons[j+1];
                    persons[j+1] = tmp;
                }
            }
        }
    }

    //定义方法,形参为Person类型,功能:调用学生的study或教师的teach方法
    public void test(Person p){
        if(p instanceof Student){//p的 运行类型如果是Student
            ((Student) p).study();
        }else if(p instanceof Teacher){
            ((Teacher) p).teach();
        }else{
            System.out.println("do nothing");
        }
    }
}

我是A类
hahah我是B类的有参构造
我是C类的有参构造
我是c类的无参构造

Homework15.java

package com.hspedu.homework;

public class Homework15 {
    public static void main(String[] args) {
        AAA obj =new BBB(); //向上转型
        AAA b1 = obj;
        System.out.println("obj的运行类型=" + obj.getClass());//BBB
        obj = new CCC();//向上转型
        System.out.println("obj的运行类型=" + obj.getClass());//CCC
        obj = b1;
        System.out.println("obj的运行类型=" + obj.getClass());//BBB
    }
}
class AAA{

}
class BBB extends AAA{

}
class CCC extends BBB {

}

 

赞(2)

评论 抢沙发

评论前必须登录!

 

LNMP社群 不仅仅是技术

关于我们网站地图