多态
/**
* 父类
*/
class BaseClass {
void printBase() {
System.out.println("i am a base method");
}
void printStr() {
System.out.println("i am a method in BaseClass!");
}
}
/**
* 子类
*/
class SubClass extends BaseClass {
@Override
void printStr() {
System.out.println("i am a method in SubClass!");
}
void printSub() {
System.out.println("i am a sub method");
}
}
/**
* 多态的代码理解
*/
public class Polymorphism {
public static void main(String[] args) {
// 父类自身调用自身的类方法
BaseClass bs = new BaseClass();
bs.printBase(); // i am a base method
bs.printStr(); // i am a method in BaseClass!
// 子类自身调用自身的类方法
SubClass sc = new SubClass();
sc.printStr(); // i am a method in SubClass!
sc.printSub(); // i am a sub method
sc.printBase(); // i am a base method
// 多态
BaseClass polymorphism = new SubClass();
// 父类对象调用子类方法
polymorphism.printStr(); // i am a method in SubClass!
// 父类对象调用自身方法
polymorphism.printBase(); // i am a base method
}
}
组合
class HumanClass {
void breath() {
System.out.println("breath ~");
}
void sleep() {
System.out.println("sleep ~");
}
void eat() {
System.out.println("eat ~");
}
}
class StuClass {
private HumanClass human;
StuClass(HumanClass human) {
this.human = human;
}
void breath() {
human.breath();
}
void study() {
System.out.println("study ~");
}
}
class WorkerClass {
private HumanClass human;
WorkerClass(HumanClass human) {
this.human = human;
}
void eat() {
human.eat();
}
void work() {
System.out.println("work ~");
}
}
public class Combination {
public static void main(String[] args) {
HumanClass jack = new HumanClass();
jack.eat();
jack.breath();
jack.sleep();
StuClass jess = new StuClass(jack);
jess.breath();
jess.study();
WorkerClass li = new WorkerClass(jack);
li.eat();
li.work();
}
}
继承
/**
* 父类
*/
class HumanClass {
void breath() {
System.out.println("breath ~");
}
void sleep() {
System.out.println("sleep ~");
}
void eat() {
System.out.println("eat ~");
}
}
/**
* 子类
*/
class StuClass extends HumanClass {
void study() {
System.out.println("study ~");
}
}
class WorkerClass extends HumanClass{
void work() {
System.out.println("work ~");
}
}
public class Inherit {
public static void main(String[] args) {
HumanClass jack = new HumanClass();
jack.breath();
jack.eat();
jack.sleep();
StuClass jess = new StuClass();
jess.study();
jess.breath();
jess.eat();
jess.sleep();
WorkerClass li = new WorkerClass();
li.work();
li.breath();
li.eat();
li.sleep();
}
}
网友评论