面向对象
Person
// 描述人类信息 class Person { String name; // 姓名 int age; // 年龄 static int totalNum = 70; // 表示人的总数 // 工作 void work() { System.out.println("工作...."); } // 毁灭 static void destory() { System.out.println("毁灭....."); } } // 演示类/测试类 public class PersonDemo { public static void main(String[] args) { Person p1 = new Person(); p1.name = "乔峰"; p1.age = 32; Person p2 = new Person(); p2.name = "阿朱"; p2.age = 19; System.out.println(p1.name + "," + p1.age); System.out.println(p2.name + "," + p2.age); System.out.println("----------------------------------------"); System.out.println(p1.totalNum); // 底层依然使用Person.totalNum来访问. System.out.println(p2.totalNum); System.out.println(Person.totalNum); System.out.println("----------------------------------------"); p1.totalNum = 10; System.out.println(p1.totalNum); // 10 System.out.println(p2.totalNum); // 10 System.out.println(Person.totalNum); // 10 } }
Servant
// 描述菲佣信息 class Servant { String name; // 名字 int age; // 年龄 // 购物 void shopping() { System.out.println("购物"); } // 做饭 void cook() { System.out.println("做饭"); } // 洗碗 void wash() { System.out.println("洗碗"); } } // 程序员 class Coder{ // 写代码 void coding() { System.out.println("开发一个游戏"); } } // 操作菲佣对象 public class ServantDemo { public static void main(String[] args) { // 创建菲佣对象 Servant s1 = new Servant(); // 给对象的字段设置值 s1.name="乔峰"; s1.age=33; // 获取对象的字段的值 Servant s2 = new Servant(); s2.name="乔峰"; s2.age=33; System.out.println(s1 == s2); // false System.out.println(s1.name+","+s1.age); System.out.println("---------------------------------"); Servant ss2 = new Servant(); ss2.name="西门吹雪"; ss2.age=28; System.out.println(ss2.name+","+ss2.age); System.out.println("---------------------------------"); Servant ss3 = new Servant(); ss3.name="陆小凤"; ss3.age=26; System.out.println(ss3.name+","+ss3.age); System.out.println("---------------------------------"); // 把s2所引用的地址值赋给s1变量 s1 = ss2; System.out.println(s1.name+","+s1.age); System.out.println(ss2.name+","+ss2.age); // 此时s3变量没有引用任何堆中的内存空间 ss3 = null; // System.out.println(ss3.name+","+ss3.age); } }
Static
// 演示static成员和非static成员的访问 public class StaticDemo { String msg = "非static成员变量"; static String staticMsg = "static成员变量"; static String info = null; static boolean flag = false; void doWork(){ System.out.println(msg); System.out.println(staticMsg); staticDoWork(); } static void staticDoWork() { System.out.println("staticDoWork"); } public static void main(String[] args) { System.out.println(info); System.out.println(flag); // System.out.println(msg); // 错误:无法从静态上下文中引用非静态方法 变量msg System.out.println(staticMsg); // static成员变量 // doWork(); // 错误:无法从静态上下文中引用非静态 方法 doWork staticDoWork(); new StaticDemo().doWork(); } }
Student
/** * 需求: * 学生类(Student)有两个字段:name(名字)和isFee(是否交学费的状态),有一个方法:交学费(fees)。 * 每一个学生都是通过Student类new出来的一个对象,现在创建一个数组存放学生对象,再分别调用该数组里的这些学生交学费的方法。 */ // 描述学生信息的类 class Student { String name = null; // 名称 boolean isFee = false; // 是否已经缴学费 // 缴学费 void fees() { isFee = true; // 修改是否缴学费的状态 } Student() { System.out.println("AA"); } Student(String n) { name = n; } } // 测试 public class StudentDemo { public static void main(String[] args) { Student ss = new Student("小明"); Student s1 = new Student(); s1.name = "赵一"; s1.isFee = false; Student s2 = new Student(); s2.name = "钱二"; // 设置已经缴学费的状态 s2.isFee = true; Student s3 = new Student(); s3.name = "孙三"; s3.isFee = false; Student s4 = new Student(); s4.name = "李四"; s4.isFee = false; Student s5 = new Student(); s5.name = "周五"; s5.isFee = false; System.out.println(s5.isFee); // 把以上5个学生对象,存放到一个容器中(数组) Student[] students = new Student[]{s1, s2, s3, s4, s5}; for (Student s : students) { // 判断学生是否已经缴费,若没有,则调用其缴费的方法 if (!s.isFee) { s.fees(); // 缴费 } } System.out.println(s5.isFee); // 集合/数组中存储元素,其实存储的是该对象的引用地址 System.out.println(students[4] == s5); // true } }
Animal
// 动物 class Animal { Animal(){} void slepp() { System.out.println("睡觉,zzzzzz......."); } } // 狗 class Dog extends Animal { void watch() { System.out.println("看门........."); slepp(); } } // 猫 class Cat extends Animal { void catchMouse() { System.out.println("逮老鼠"); slepp(); } } public class AnimalDemo { public static void main(String[] args) { Dog dog = new Dog(); dog.watch(); Cat cat = new Cat(); cat.catchMouse(); } }
Extends
// 人类 class Persons { String name; // 姓名 int age; // 年龄 // 省略Getter/Setter } // 老师类 class Teacher extends Persons { private String staffid; // 工号 private String hirDate; // 入职时间 } // 学生类 class Student extends Persons { private String stuid; // 学号 } // 员工类 class Employee extends Persons { private String empid; // 工号 private String hirDate; // 入职时间 } public class ExtendsDemo { public static void main(String[] args) { System.out.println("Hello"); } }
Import
import java.util.Arrays; import java.util.List; import java.util.Set; public class ImportDemo { public static void main(String[] args) { int[] arr1 = {1,2,3,4,5}; String ret = Arrays.toString(arr1); System.out.println(ret); System.out.println(Arrays.toString(arr1)); Set set = null; List list = null; System.out.println(Math.max(30,20)); // 最大值 System.out.println(Math.min(30,20)); // 最小值 } }
Object
class Duck { private String name = "小丑鸭"; private int age = 11; // 覆盖Object的toString方法 public String toString(){ return this.name+","+this.age; } } public class ObjectDemo { public static void main(String[] args) { String str1 = "AA"; String str2 = "AA"; System.out.println(str1 == str2); // true System.out.println("-----------------"); String s1 = new String("AA"); String s2 = new String("AA"); System.out.println(s1 == s2); // false System.out.println("------------------"); boolean ret = s1.equals(s2); System.out.println(ret); // true System.out.println("--------------"); Duck duck = new Duck(); System.out.println(duck); // 小丑鸭,11 System.out.println(duck.toString()); // 小丑鸭,11 } }
Override
// 鸟类 class Bird { protected void fly() { System.out.println("我要飞得更高!!!"); } } // 企鹅 class Penguin extends Bird { @Override public void fly() { System.out.println("我是折翼的天使,飞不动!!!"); } // 企鹅特有的方法 public void swimming() { super.fly(); System.out.println("游泳,很凉快..."); } } // 方法的覆盖 public class OverrideDemo { public static void main(String[] args) { Penguin p = new Penguin(); // p.fly(); p.swimming(); } }
Person
class Person{ String name; int age; // 专门给age字段设置值 public void setAge(int a) { if (a < 0) { System.out.println("年龄不能为负数"); return;// 结束方法 } age = a; } } // 封装思想 public class PersonDemo { public static void main(String[] args) { // 创建一个Person对象,给年龄赋值,再打印年龄值 Person p1 = new Person(); // 数据不合理,没有做检查 p1.setAge(-16); System.out.println(p1.age); } }
class Person2{ private String name = "小明"; private int age; // 向外暴露获取name的值 public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int a) { if (a<0) { System.out.println("年龄不能小于0"); return; } age = a; } } // 封装思想 public class PersonDemo2 { public static void main(String[] args) { Person2 p = new Person2(); p.setName("Will"); String name = p.getName(); p.setAge(17); System.out.println(name); } }
Super
// 父类 class SuperClass{ SuperClass(){ System.out.println("SuperClass构造器...."); } } // 子类 class SubClass extends SuperClass{ SubClass() { super(); // 默认会调用父类无参数构造器 System.out.println("SubClass构造器...."); } } // super关键字 public class SuperDemo { public static void main(String[] args) { // 创建子类对象 SubClass sub = new SubClass(); } }
// 动物 class Animals { private String name; private int age; Animals(String name, int age) { this.name = name; this.age = age; } public void say() { System.out.println(this.name + ",今年" + this.age + "岁"); } } // 鱼 class Fish extends Animals { private String color; // 颜色 Fish(String name, int age, String color) { super(name, age); // 调用父类构造器 } // 说:名字,年龄,颜色 public void say() { super.say(); // 调用父类的say方法 System.out.println("我的颜色是" + color); } } public class SuperDemo2 { public static void main(String[] args) { Fish f = new Fish("尼莫", 3, "红色"); f.say(); } }
This
public class ThisDemo { private String name = "成员变量"; private int age; public ThisDemo() { this(null, 0); // 调用ThisDemo(String name, int age) System.out.println("无参数构造器"); } public ThisDemo(String name) { this(); // 调用ThisDemo() System.out.println(111); } public ThisDemo(String name, int age) { this.name = name; this.age = age; } public void show() { System.out.println("show方法"); } public ThisDemo append() { return this; } public void doWork() { this.show(); String name = "局部变量"; System.out.println(name); // 局部变量 System.out.println(this.name); // 成员变量 } public static void main(String[] args) { new ThisDemo("乔峰", 25); } }
// 描述了用户对象 class User{ private String name; private int 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 class UserDemo { public static void main(String[] args) { // 创建一个User对象,给该对象设置名字为Lucy User u1 = new User(); u1.setName("Lucy"); System.out.println(u1.getName()); } }
Abstract
// 圆形 class Graph{ // 图像都有求面积的行为 public double getArea(){ return 0.0; } } // 圆 class Circle{ private int r; // 半径 Circle(int r){ this.r = r; } // 求面积 public double getArea(){ return 3.14 * r * r; } } // 矩形 class Rectangle{ private int width; private int height; Rectangle(int width,int height){ this.width = width; this.height = height; } // 求面积 public double getArea(){ return width * height; } } // 三角形 class Triangle extends Graph { private Integer a; private Integer b; private Integer c; Triangle(Integer a, Integer b, Integer c) { this.a = a; this.b = b; this.c = c; } // 求面积 public double getArea() { // 秦九昭公式 return 100; } } public class AbstractDemo { public static void main(String[] args) { // 求圆的面积 System.out.println("圆的面积"); System.out.println(new Circle(10).getArea()); // 314.0 // 求矩形的面积 System.out.println("矩形的面积"); System.out.println(new Rectangle(10,6).getArea()); // 60.0 // 求三角形的面积 System.out.println("三角形面积"); Triangle tri = new Triangle(3,4,5); System.out.println(tri.getArea()); // 100.0 } }
Animal
// 动物类 class Animal { public void eat() { System.out.println("吃一般的食物"); } } // 狗类 class Dog extends Animal { public void eat() { System.out.println("吃狗粮..."); } public void watch() { System.out.println("看门..."); } } // 猫类 class Cat extends Animal { public void eat() { System.out.println("吃猫粮..."); } public void catchMouse(){ System.out.println("逮老鼠...."); } } // 人类 class Person { // 喂养任何动物 public void feed(Animal a) { // 判断a是Dog类型还是Cat类型,不同的类型完成不同的功能 System.out.println("....feeding...."); a.eat(); // 吃食物 if (a instanceof Dog) { Dog d = (Dog) a; // 强转 d.watch(); } else if (a instanceof Cat) { Cat c = (Cat) a; // 强转 c.catchMouse(); } } } public class AnimalDemo { public static void main(String[] args) { // 创建一个饲养员对象 Person p = new Person(); p.feed(new Dog()); System.out.println("----------"); p.feed(new Cat()); } }
Code
// 代码块 public class CodeDemo { { System.out.println("初始化代码块"); } CodeDemo(){ System.out.println("构造器"); } static { System.out.println("静态代码块"); } public static void main(String[] args) { System.out.println("....main......"); if (true) { System.out.println("局部代码块"); } new CodeDemo(); } }
Final
class SuperClass { SuperClass() { init(); } public void init() { System.out.println("初始化操作"); } } class SubClass extends SuperClass { // 覆盖 public void init() { System.out.println("做自己的初始化操作"); } } // final修饰符 public class FinalDemo { public static void main(String[] args) { final User user = new User(); System.out.println(user); user.setName("乔峰"); System.out.println(user); } } class User{ String name="小明"; public void setName(String name) { this.name = name; } // 覆盖 public String toString() { return this.name; } }
FlyWeight
// 包装类的缓存机制 public class FlyWeightDemo { public static void main(String[] args) { Integer i1 = 125; Integer i2 = 125; // 判断两个Integer是否相等 // 比较是两个对象使用引用同一块内存空间 System.out.println(i1 == i2); // true // 比较内容 System.out.println(i1.equals(i2)); // true System.out.println("----------------"); Integer i3 = new Integer(125); Integer i4 = new Integer(125); System.out.println(i3 == i4); // false System.out.println(i3.equals(i4)); // true } }
Integer
public class IntegerDemo { public static void main(String[] args) { // 装箱/拆箱 Integer num1 = new Integer(17); int num5 = num1.intValue(); Integer num2 = Integer.valueOf(17); // 自动装箱/拆箱 Integer num3 = 17; int um4 = num3; System.out.println(num5 == num1); // true System.out.println(num2 == num1); // false System.out.println(num5 == num2); // true System.out.println(um4==num1); // true Integer num = 3; switch (num) { case 1: break; case 2: break; case 3: break; } System.out.println("====================="); System.out.println(Integer.MAX_VALUE); // 2147483647 } }
IntWapper
// 设计int类型的包装类 class IntWapper { private int value; // 被包装的int值 // int的最大/小值 public static final int MAX_VALUE = 2147483647; public static final int MIN_VALUE = -2147483648; IntWapper(int value) { this.value = value; } // 转换为二进制 public String toBinaryString(int value) { return "OB00100101"; } } public class IntWapperDemo { public static void main(String[] args) { IntWapper wapper1 = new IntWapper(17); // 包装17 IntWapper wapper2 = new IntWapper(95); // 包装95 System.out.println(IntWapper.MAX_VALUE); // 2147483647 System.out.println(IntWapper.MIN_VALUE); // -2147483648 } }
ClassInClass
class MyLinkedList { // 非静态内部类 class MyNode1 {} // 静态内部类 static class MyNode2 {} } class Tiger implements IWalkable { public void walk() { System.out.println("老虎走路"); } } public class ClassInClassDemo { public static void main(String[] args) { // 局部内部类 class MyClass3 {} // 需求:调用xxx类中的show方法 // xxx.show(new Tiger()); // 需求:不想为Dog类定义,只想使用一次就行了 xxx.show(new IWalkable() { public void walk() { System.out.println("狗狗走路"); } }); } } class xxx { public static void show(IWalkable animal) { animal.walk(); } }
EnumMock
// 员工 class Employee { // 休息日 private Weekday restDay; public Weekday getRestDay() { return restDay; } public void setRestDay(Weekday restDay) { this.restDay = restDay; } } // 专门用于表示周1到周7 enum Weekday { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY; } public class EnumMock { public static void main(String[] args) { // 创建一个员工对象,设置一个休息日(星期几) Employee e = new Employee(); e.setRestDay(Weekday.SATURDAY); // 周1休息 if (e.getRestDay() == Weekday.SATURDAY || e.getRestDay() == Weekday.SUNDAY) { System.out.println("周末休息"); } else { System.out.println("周1到周5休息"); } System.out.println("---------------"); // 获取枚举类型所有的对象常量 Weekday[] days = Weekday.values(); System.out.println(days.length); // 2):把一个字符串转换为枚举的常量对象 Weekday saturday = Weekday.valueOf("SATURDAY"); System.out.println(saturday); System.out.println(saturday.name()); System.out.println(saturday.ordinal()); System.out.println("-------------------"); switch (Weekday.MONDAY) { case MONDAY : System.out.println("周一"); break; case THURSDAY : System.out.println("周四"); break; } } }
Interface
// 可以走路的行为 interface IWalkable { void walk(); } // 会游泳 interface ISwimable { void swim(); } // 鱼 class Fish implements ISwimable { public void swim() { System.out.println("游啊游..."); } } // 猫具有走路的行为 class Cat implements IWalkable { public void walk() { System.out.println("走猫步...."); } } // 青蛙 class Frog implements ISwimable, IWalkable { public void walk() { System.out.println("跳步.."); } public void swim() { System.out.println("..蛙泳.."); } } public class InterfaceDemo { public static void main(String[] args) { // 多态:接口和实现的关系 IWalkable cat = new Cat(); cat.walk(); ISwimable fish = new Fish(); fish.swim(); Frog frog = new Frog(); frog.swim(); frog.walk(); } }
TotalTime
// 操作模板 abstract class OperateTemplate { // 模板方法:提供了统一的算法骨架 public final long getTotalTime() { // 1.获取当前系统时间毫秒数 long begin = System.currentTimeMillis(); // 2.各自的操作(累加/连接) doWork(); // 子类具有的操作 // 3.获取当前系统时间毫秒数 long end = System.currentTimeMillis(); // 4.返回时间差(第二步操作耗时) return end - begin; } // 专门留给子类去实现(不同的子类实现细节不同) abstract protected void doWork(); } // int类型操作 class IntOperate extends OperateTemplate { public void doWork() { long total = 0; // 总和 for (int i = 1; i <= 50000; i++) { total += i; // 累加 } } } // String操作 class StringOperate extends OperateTemplate { public void doWork() { String str = ""; for (int i = 1; i <= 50000; i++) { str = str + i; } } } // 计算操作耗时 public class TotalTimeDemo { public static void main(String[] args) { System.out.println(new IntOperate().getTotalTime()); System.out.println(new StringOperate().getTotalTime()); } }