多态
public class Hello {
public static void main(String[] args) {
Animal d = new Dog();
Animal c = new Cat();
eat(c);
eat(d);
eat(new Dog());
}
private static void eat(Animal a) {
a.eat();
}
// private static void eat(Cat c) {
// c.eat();
// }
//
// private static void eat(Dog d) {
// d.eat();
// }
}
abstract class Animal {
abstract void eat();
}
class Cat extends Animal {
void eat() {
System.out.println("我吃鱼!");
}
}
class Dog extends Animal {
void eat() {
System.out.println("我吃骨头!");
}
}
多态转型:
向上转型是因为父类引用指向子类对象,自始至终都是子类对象在做变化。所以可以转换。
多态中成员的特点:
public class Hello {
public static void main(String[] args) {
Animal a = new Cat();
a.eat();
}
}
class Animal {
void eat() {
System.out.println("eat方法");
}
}
class Cat extends Animal {
void eat() {
System.out.println("我吃鱼!");
}
void sleep() {
System.out.println("我在睡觉!");
}
}
sleep是子类中特有的方法,父类中并没有,所以
Animal a = new Cat();
a.eat();
a不能调用sleep方法
并且执行的是子类重写之后的方法。
Object类
Object是所有对象的直接或者间接父类。由此可见,该类中的方法是所有对象都具有的方法,因为所有对象都继承自此类。
内部类
内部类可以用私有修饰
public class Hello {
public static void main(String[] args) {
Outer.Inner inner = new Outer().new Inner();//要加上Outer才能明确
inner.show();
}
}
class Outer {
class Inner {
void show() {
System.out.println("我是内部类!");
}
}
}
public class Hello {
public static void main(String[] args) {
Outer.Inner inner = new Outer().new Inner();
inner.show();
}
}
class Outer {
int x = 3;
class Inner {
int x = 4;
void show() {
int x = 5;
System.out.println(x);
System.out.println(this.x);
System.out.println(Outer.this.x);
}
}
}
打印结果:5 4 3
匿名内部类
暂时到这里,匿名内部类后边会补充。