继承体系下除了overridden 技术外使得子类与父类表现出不同行为外,反射也可以,而且反射使得继承不需要overridden

/**
 * This small example is more dramatic than it seems—it contains each of the
 * steps previously mentioned. The printName method examines the object for its
 * class (this.getClass()). In doing so, the decision of what to print is made by del-
 * egating to the object’s class. The method acts on this decision by printing the
 * returned name. Without being overridden, the printName method behaves differ-
 * ently for each subclass than it does for HelloWorld. The printName method is flex-
 * ible; it adapts to the class that inherits it, causing the change in behavior. As we
 * build our examples in scope and complexity, we will show you many more ways to
 * attain flexibility using reflection.
 * 
 * 继承体系下除了overridden 技术外使得子类与父类表现出不同行为外,反射也可以,而且反射使得继承不需要overridden。
 * 
 * @author doctor
 *
 * @time 2014年11月28日 上午8:54:05
 */

public class GetClassPractice {

	public static void main(String[] args) {
		new HelloWorld().printName();
		new HelloWorldChild1().printName();
		new HelloWorldChild2().printName();
		
		System.out.println(new HelloWorld().getClassType());
		System.out.println(new HelloWorldChild1().getClassType());
		System.out.println(new HelloWorldChild2().getClassType());
		
		System.out.println("接口");
		new Hello1().printName();
		new Hello2().printName();

	}

	public static class HelloWorld {
		public void printName() {
			System.out.println(getClass().getName());
		}
		
		public  Class<? extends HelloWorld> getClassType(){
			return getClass();
		}
	}

	public static class HelloWorldChild1 extends HelloWorld {

	}

	public static class HelloWorldChild2 extends HelloWorld {

	}

	public interface Hello{
		public default void printName(){
			System.out.println(getClass().getName());
		}
	}
	
	public static class Hello1 implements Hello{
		
	}
	public static class Hello2 implements Hello{
		
	}
}



com.github.ebook.javarefectioninaction.GetClassPractice$HelloWorld
com.github.ebook.javarefectioninaction.GetClassPractice$HelloWorldChild1
com.github.ebook.javarefectioninaction.GetClassPractice$HelloWorldChild2
class com.github.ebook.javarefectioninaction.GetClassPractice$HelloWorld
class com.github.ebook.javarefectioninaction.GetClassPractice$HelloWorldChild1
class com.github.ebook.javarefectioninaction.GetClassPractice$HelloWorldChild2
接口
com.github.ebook.javarefectioninaction.GetClassPractice$Hello1
com.github.ebook.javarefectioninaction.GetClassPractice$Hello2

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Dreamer who

你的鼓励将是我创作的最大动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值