public class MainJava {
public static void main(String[] args) {
//定義父類數組
Wine[] wines = new Wine[2];
//定義兩個子類
Test1 test1 = new Test1();
Test2 test2 = new Test2();
Wine win e = new Wine();
//父類引用子類對象
wines[0] = test1;
wines[1] = test2;
for(int i = 0 ; i < 2 ; i++){
System.out.println(wines[i].toString() + "--" + wines[i].drink());
}
System.out.println("-------------------------------");
System.out.println(test1.toString() + "--" + test1.drink());
System.out.println(test2.toString() + "--" + test2.drink());
}
public static class Wine {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String drink(){
return "喝的是 " + getName();
}
public String toString(){
return null;
}
}
public static class Test1 extends Wine{
public Test1(){
setName("Test1");
}
public String drink(){
return "喝的是 " + getName();
}
public String toString(){
return "Wine : " + getName();
}
}
public static class Test2 extends Wine{
public Test2(){
setName("Test2");
}
public String drink(){
return "喝的是 " + getName();
}
public String toString(){
return "Wine : " + getName();
}
}
}
複製代碼
class Demo_SuperMan {
public static void main(String[]args){
Person p=new SuperMan();//父類引用指向子類對象。超人提高爲了人
//父類引用指向子類對象,就是向上轉型
System.out.println(p.name);
p.Tsy();
//p.Fly();//找不到該方法
SuperMan sm=(SuperMan)p;//向下轉型,看到整個對象的內容
sm.Fly();
}
}
class Person{
String name="John";
public void Tsy(){
System.out.println("Tsy");
}
}
class SuperMan extends Person{
String name="SuperName";
@Override
public void Tsy(){
System.out.println("子類Tsy");
}
public void Fly(){
System.out.println("飛出去救人");
}
}
複製代碼
public class VIPCenter {
void serviceVIP(T extend User user>) {
if (user instanceof SlumDogVIP) {
// 窮 X VIP,活動搶的那種
// do somthing
} else if(user instanceof RealVIP) {
// do somthing
}
// ...
}
複製代碼
public class VIPCenter {
private Map<User.TYPE, ServiceProvider> providers;
void serviceVIP(T extend User user) {
providers.get(user.getType()).service(user);
}
}
interface ServiceProvider{
void service(T extend User user) ;
}
class SlumDogVIPServiceProvider implements ServiceProvider{
void service(T extend User user){
// do somthing
}
}
class RealVIPServiceProvider implements ServiceProvider{
void service(T extend User user) {
// do something
}
}
複製代碼
public abstract class AbstractClassExample {
protected int x;
private int y;
public abstract void func1();
public void func2() {
System.out.println("func2");
}
}
public class AbstractExtendClassExample extends AbstractClassExample {
@Override
public void func1() {
System.out.println("func1");
}
}
複製代碼
private void test1(){
Demo demo = new Demo();
demo.change(demo.str, demo.ch);
Log.d("yc---",demo.str);
Log.d("yc---", Arrays.toString(demo.ch));
//打印值
//yc---: hello
//yc---: [c, b]
}
public class Demo {
String str = new String("hello");
char[] ch = {'a', 'b'};
public void change(String str, char[] ch) {
str = "ok";
ch[0] = 'c';
}
}
複製代碼