Java知识点细节简易汇总——(8)枚举和注解+Java面向对象高级作业

一、枚举

自定义枚举
在这里插入图片描述

  1. 当我们使用 enum 关键字开发一个枚举类时,默认会继承 Enum 类, 而且是一个 final 类[如何证明],老师使用 javap 工具来演示
  2. 传统的 public static final Season2 SPRING = new Season2(“春天”, “温暖”); 简化成 SPRING(“春天”, “温暖”), 这里必须知道,它调用的是哪个构造器.
  3. 如果使用无参构造器 创建 枚举对象,则实参列表和小括号都可以省略
  4. 当有多个枚举对象时,使用,间隔,最后有一个分号结尾
  5. 枚举对象必须放在枚举类的行首.
package Null;

public class B {
	public static void main(String[] args) {
		System.out.println(Season.AUTUMN);
		System.out.println(Season.SPRING);
	}
}

class Season {// 类
	private String name;
	private String desc; // 描述
	
	/*
	 *步骤
	 * 1. 将构造器私有化,目的防止 直接 new
	 * 2. 去掉 setXxx 方法, 防止属性被修改
	 * 3. 在 Season内部,直接创建固定的对象
	 * 4. 优化:可以加入 final 修饰符
	 */	
	//定义了四个对象, 固定
	public static final Season SPRING = new Season("春天", "温暖");
	public static final Season WINTER = new Season("冬天", "寒冷");
	public static final Season AUTUMN = new Season("秋天", "凉爽");
	public static final Season SUMMER = new Season("夏天", "炎热");
	
	private Season(String name, String desc) {
		this.name = name;
		this.desc = desc;
	}
	public String getName() {
		return name;
	}
	public String getDesc() {
		return desc;
	}
	@Override
	public String toString() {
		return "Season{" + "name='" + name + '\'' + ", desc='" + desc + '\'' + '}';
	}
}

枚举类

public static void main(String[] args) {
		System.out.println(Season.AUTUMN);
	}
}

enum Season {// 类
	
	/*
	 * 如果使用了 enum 来实现枚举类 
	 * 1. 使用关键字 enum 替代 class
	 * 2. public static final Season SPRING = new Season("春天", "温暖") 直接使用 
	 * 	  SPRING("春天", "温暖") 解读 常量名(实参列表) 
	 * 3.如果有多个常量(对象), 使用 ,号间隔即可
	 * 4.如果使用 enum 来实现枚举,要求将定义常量对象,写在 最前面 
	 * 5.如果我们使用的是无参构造器,创建常量对象,则可以省略 ()
	 */	
	SPRING("春天", "温暖"), WINTER("冬天", "寒冷"), AUTUMN("秋天", "凉爽"), SUMMER("夏天", "炎热"); 
	
	private String name;
	private String desc; // 描述
	
	private Season(String name, String desc) {
		this.name = name;
		this.desc = desc;
	}

	public String getName() {
		return name;
	}

	public String getDesc() {
		return desc;
	}
	@Override
	public String toString() {
		return "Season{" + "name='" + name + '\'' + ", desc='" + desc + '\'' + '}';
	}
}

enum 常用的方法:

  1. toString:Enum 类已经重写过了,返回的是当前对象 名,子类可以重写该方法,用于返回对象的属性信息
  2. name:返回当前对象名(常量名),子类中不能重写
  3. ordinal:返回当前对象的位置号,默认从 0 开始
  4. values:返回当前枚举类中所有的常量
  5. valueOf:将字符串转换成枚举对象,要求:1. 根据你输入的"字符串"到 Season 的枚举对象去查找
    2.如果找到了,就返回,如果没有找到,就报
  6. compareTo:比较两个枚举常量,比较的就是编号

二、注解

  1. @Override: 限定某个方法,是重写父类方法, 该注解只能用于方法
  2. @Deprecated: 用于表示某个程序元素(类, 方法等)已过时,即不在推荐使用,但是仍然可以使用
  3. @SuppressWarnings: 抑制编译器警告信息

三、Java面向对象高级作业:

在这里插入图片描述
在这里插入图片描述

public class Homework {
    public static void main(String[] args) {
        
        //老韩解读
        //1. 匿名内部类是
        /*
            new ICalculate() {
                @Override
                public double work(double n1, double n2) {
                    return n1 + n2;
                }
            }, 同时也是一个对象
                         他的编译类型 ICalculate, 他的运行类型就是 匿名内部类
         */
        Cellphone cellphone = new Cellphone();
        cellphone.testWork(new ICalculate() {
            @Override
            public double work(double n1, double n2) {
                return n1 + n2;
            }
        }, 10, 8);//18.0

        cellphone.testWork(new ICalculate() {
            @Override
            public double work(double n1, double n2) {
                return n1 * n2;
            }
        }, 10, 8);
    }
}
/*
1.计算器接口具有work方法,功能是运算,有一个手机类Cellphone,
   定义方法testWork测试计算功能,调用计算接口的work方法,
2.要求调用CellPhone对象 的testWork方法,使用上 匿名内部类

 */
//编写接口
interface ICalculate {
    //work方法 是完成计算,但是题没有具体要求,所以自己设计
    //至于该方法完成怎样的计算,我们交给匿名内部类完成
    public double work(double n1, double n2) ;
}
class Cellphone {
    //老韩解读,当我们调用testWork方法时,直接传入一个实现了ICalculate接口的匿名内部类即可
    //该匿名内部类,可以灵活的实现work,完成不同的计算任务
    public void testWork(ICalculate iCalculate, double n1, double n2) {
        double result = iCalculate.work(n1, n2);//动态绑定
        System.out.println("计算后的结果是=" + result);
    }
}

在这里插入图片描述

Vehicles接口:

public interface Vehicles {
    //有一个交通工具接口类Vehicles,有work接口
    public void work();
}

Horse 类

public class Horse implements Vehicles {
    @Override
    public void work() {
        System.out.println(" 一般情况下,使用马儿前进...");
    }
}

Boat 类

public class Boat implements Vehicles {
    @Override
    public void work() {
        System.out.println(" 过河的时候,使用小船.. ");
    }
}

VehiclesFactory 类

public class VehiclesFactory {
    //马儿始终是同一匹
    private static Horse horse = new Horse(); //饿汉式

    private VehiclesFactory(){}
    //创建交通工具工厂类,有两个方法分别获得交通工具Horse和Boat
    //这里,我们将方法做成static
    public static Horse getHorse() {
//        return new Horse();
        return horse;
    }
    public static Boat getBoat() {
        return new Boat();
    }
    public static Plane getPlane() {
        return new Plane();
    }
}

public class Person {
    private String name;
    private Vehicles vehicles;

    //在创建人对象时,事先给他分配一个交通工具
    public Person(String name, Vehicles vehicles) {
        this.name = name;
        this.vehicles = vehicles;
    }

    //思考一个问题,如何不浪费,在构建对象时,传入的交通工具对象->动脑筋
    public void passRiver() {
        //如何防止始终使用的是传入的马 instanceOf
        //vehicles instanceof Boat 是判断 当前的 vehicles是不是Boat
        //(1) vehicles = null  : vehicles instanceof Boat  => false
        //(2) vehicles = 马对象 :vehicles instanceof Boat  => false
        //(3) vehicles = 船对象 :vehicles instanceof Boat  => true
        if (!(vehicles instanceof Boat)) {
            vehicles = VehiclesFactory.getBoat();
        }
        vehicles.work();
    }

    public void common() {
        //得到马儿
        //判断一下,当前的 vehicles 属性是null, 就获取一匹马
        //if (vehicles == null) {
        if (!(vehicles instanceof Horse)) {
            //这里使用的是多态
            vehicles = VehiclesFactory.getHorse();
        }
        //这里体现使用接口调用
        vehicles.work();
    }
    //过火焰山
    public void passFireHill() {
        if (!(vehicles instanceof Plane)) {
            //这里使用的是多态
            vehicles = VehiclesFactory.getPlane();
        }
        //这里体现使用接口调用
        vehicles.work();

    }
}
//有Person类,有name和Vehicles属性,在构造器中为两个属性赋值
public class Homework06 {
    public static void main(String[] args) {
        Person tang = new Person("唐僧", new Horse());
        tang.common();//一般情况下
        tang.passRiver();//过河
        //过火焰山
        tang.passFireHill();
    }
}
/*
1.有一个交通工具接口类Vehicles,有work接口
2.有Horse类和Boat类分别实现Vehicles
3.创建交通工具工厂类,有两个方法分别获得交通工具Horse和Boat
4.有Person类,有name和Vehicles属性,在构造器中为两个属性赋值
5.实例化Person对象“唐僧”,要求一般情况下用Horse作为交通工具,遇到大河时用Boat作为交通工具
6.增加一个情况,如果唐僧过火焰山, 使用 飞机 ==> 程序扩展性, 我们前面的程序结构就非常好扩展 10min
使用代码实现上面的要求
编程 需求---->理解---->代码-->优化
 */


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是一个 Java 示例代码,使用注解+反射+枚举实现字典方法: ```java import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.reflect.Field; import java.util.HashMap; import java.util.Map; @Retention(RetentionPolicy.RUNTIME) @interface DictionaryEntry { String key(); String value(); } enum Dictionary { FRUIT, COLOR, ANIMAL; } public class Main { private static Map<String, Map<String, String>> dictionaryMap = new HashMap<>(); public static void main(String[] args) { initDictionary(); String fruitName = "apple"; String fruitColor = getDictionaryValue(Dictionary.FRUIT, fruitName); System.out.println(fruitName + " is " + fruitColor); String colorName = "red"; String colorHex = getDictionaryValue(Dictionary.COLOR, colorName); System.out.println(colorName + " is " + colorHex); String animalName = "dog"; String animalSound = getDictionaryValue(Dictionary.ANIMAL, animalName); System.out.println(animalName + " says " + animalSound); } private static void initDictionary() { // Fruit dictionary Map<String, String> fruitMap = new HashMap<>(); fruitMap.put("apple", "red"); fruitMap.put("banana", "yellow"); fruitMap.put("orange", "orange"); dictionaryMap.put(Dictionary.FRUIT.name(), fruitMap); // Color dictionary Map<String, String> colorMap = new HashMap<>(); colorMap.put("red", "#FF0000"); colorMap.put("green", "#00FF00"); colorMap.put("blue", "#0000FF"); dictionaryMap.put(Dictionary.COLOR.name(), colorMap); // Animal dictionary Map<String, String> animalMap = new HashMap<>(); animalMap.put("dog", "woof"); animalMap.put("cat", "meow"); animalMap.put("bird", "tweet"); dictionaryMap.put(Dictionary.ANIMAL.name(), animalMap); } private static String getDictionaryValue(Dictionary dict, String key) { Map<String, String> dictMap = dictionaryMap.get(dict.name()); for (Map.Entry<String, String> entry : dictMap.entrySet()) { if (entry.getKey().equals(key)) { return entry.getValue(); } } return null; } static { for (Dictionary dict : Dictionary.values()) { Map<String, String> dictMap = new HashMap<>(); Class<?> dictClass; try { dictClass = Class.forName(dict.name()); } catch (ClassNotFoundException ex) { continue; } for (Field field : dictClass.getDeclaredFields()) { if (field.isAnnotationPresent(DictionaryEntry.class)) { DictionaryEntry entry = field.getAnnotation(DictionaryEntry.class); dictMap.put(entry.key(), entry.value()); } } dictionaryMap.put(dict.name(), dictMap); } } static class Fruit { @DictionaryEntry(key = "apple", value = "red") public static String APPLE; @DictionaryEntry(key = "banana", value = "yellow") public static String BANANA; @DictionaryEntry(key = "orange", value = "orange") public static String ORANGE; } static class Color { @DictionaryEntry(key = "red", value = "#FF0000") public static String RED; @DictionaryEntry(key = "green", value = "#00FF00") public static String GREEN; @DictionaryEntry(key = "blue", value = "#0000FF") public static String BLUE; } static class Animal { @DictionaryEntry(key = "dog", value = "woof") public static String DOG; @DictionaryEntry(key = "cat", value = "meow") public static String CAT; @DictionaryEntry(key = "bird", value = "tweet") public static String BIRD; } } ``` 这个例子中,我们创建了一个枚举类型 `Dictionary`,表示三个不同的字典:`FRUIT`、`COLOR`、`ANIMAL`。我们使用注解 `@DictionaryEntry` 来标记每个字典的条目,然后使用反射初始化字典。 在 `initDictionary` 方法中,我们创建了一个 `dictionaryMap`,包含了每个字典的名称和条目。我们使用反射枚举每个字典的条目,并将它们添加到 `dictionaryMap` 中。 在 `getDictionaryValue` 方法中,我们通过枚举类型 `Dictionary` 和键值 `key` 获取字典中的值。我们首先从 `dictionaryMap` 中获取对应的字典,然后遍历字典中的条目,查找与给定键值匹配的条目并返回它的值。 注意,这个例子只是一个简单的演示,实际应用中可能需要更复杂的字典结构和查询方式。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值