Compare commits

...

2 Commits

Author SHA1 Message Date
SALAH ABDULLAH阿山 f2fcd309d2 w55 1 month ago
SALAH ABDULLAH阿山 db87aee2d6 w55 1 month ago
  1. 50
      src/w6/Main.java
  2. 40
      src/w8/Main.java

50
src/w6/Main.java

@ -0,0 +1,50 @@
package w6;
// 游泳接口
interface Swimmable {
void swim();
}
// 抽象动物类
abstract class Animal {
public abstract void makeSound();
}
// 狗:继承Animal + 实现游泳接口
class Dog extends Animal implements Swimmable {
@Override
public void makeSound() {
System.out.println("小狗汪汪汪叫");
}
@Override
public void swim() {
System.out.println("小狗会游泳,正在游泳");
}
}
// 猫:只继承Animal,不实现游泳接口
class Cat extends Animal {
@Override
public void makeSound() {
System.out.println("小猫喵喵喵叫");
}
}
// 主类名改成Main!和文件名Main.java完全一致
public class Main {
public static void main(String[] args) {
// 多态测试:父类引用指向子类对象
Animal animal1 = new Dog();
Animal animal2 = new Cat();
// 多态调用叫声
animal1.makeSound();
animal2.makeSound();
// 向下转型调用游泳方法
if (animal1 instanceof Dog dog) {
dog.swim();
}
}
}

40
src/w8/Main.java

@ -0,0 +1,40 @@
package w8;
public class Main {
public static void main(String[] args) throws InterruptedException {
// Pair test
Pair<String, Integer> pair = new Pair<>("age", 25);
System.out.println("Original: " + pair);
System.out.println("Swap: " + pair.swap());
// Cache test
Cache<String, String> cache = new Cache<>(3000);
cache.put("name", "Ahmed");
System.out.println("Cache get: " + cache.get("name"));
}
}
class Pair<K, V> {
private K key;
private V value;
public Pair(K key, V value) { this.key = key; this.value = value; }
public Pair<V, K> swap() { return new Pair<>(value, key); }
public String toString() { return "Pair{" + key + "," + value + "}"; }
}
class Cache<K, V> {
private java.util.HashMap<K, CacheEntry<V>> cache = new java.util.HashMap<>();
private long defaultExpireTime;
public Cache(long t) { this.defaultExpireTime = t; }
public void put(K key, V value) {
cache.put(key, new CacheEntry<>(value, defaultExpireTime > 0 ? System.currentTimeMillis() + defaultExpireTime : 0));
}
public V get(K key) {
CacheEntry<V> entry = cache.get(key);
if (entry == null || (entry.expireTime > 0 && System.currentTimeMillis() > entry.expireTime)) return null;
return entry.value;
}
private static class CacheEntry<V> {
V value; long expireTime;
CacheEntry(V v, long e) { value = v; expireTime = e; }
}
}
Loading…
Cancel
Save