JAVA面向对象之多态
在java中,为了实现多态,允许使用一个父类型的变量来引用一个子类类型的对象,根据被引用子类对象特征的不同,得到不同的运行结果
定义接口Animal
interface Animal{
void shout();
}
class Cat implements Animal{
public void shout(){
System.out.println("喵喵喵...");
}
}
class Dog implement Animal{
public void shout(){
System.out.println("汪汪汪...");
}
}
public static void main(String[] args){
Animal an1=new Cat();
Animal an2=new Cat();
animalShout(an1);
animalShout(an2)
}
public static void animalShout(Animal an){
an.shout();
}
多态的优点:不仅解决了方法同名的问题,而且还使程序变得更加灵活,从而有效提高了程序的可扩张性和可维护性
对象类型转换
子类对象当作父类类型使用的情况,此种情况在java的语言环境中称为"向上转型“
如下:
Animal an1=new Cat();
Animal an2=new Dog();
注意:此时不能通过父类变量去调用子类中的特有方法
interface Animal{
void shout();
}
class Cat implements Animal{
public void shout(){
System.out.println("喵喵...");
}
void sleep(){
System.out.println("猫睡觉...");
}
}
public class Example14{
public static void main(String[] args){
Cat cat=new Cat();
animalShout(cat);
}
public static void animalShout(Animal animal){
animal.shout();
animal.shout();
}
上面的代码会报错,报错原因时Animal类没有定义sleep()方法
修改animalShout()方法就可以
public static void animalShout(Animal animal){
Cat cat=(Cat) animal;
cat.shout();
cat.sleep();
}
上面的这种将父类型当作子类型使用的情况在JAVA中称为”向下转型"
instanceof关键字,它可以判断一个对象是否为某个类(或接口)的实例或者子类实例
对象(或者对象引用变量) instanceof 类(接口)
如下:
public static void animalShout(Animal animal){
if(animal instanceof Cat){
Cat cat=(Cat) animal;
cat.shout();
cat.sleep();
}else{
System.out.println("the animal is not a cat")
}
}
Object类
Object类是类层次结构的根类,每个类都直接或间接继承该类
所有对象(包括数组)都实现了这个类的方法
| 方法名称 | 方法说明 |
|---|
| equals() | 指示其他某个对象是否与此对象"相等" |
| getClass() | 返回此Object的运行时类 |
| hashCode() | 返回该对象的哈希码值 |
| toString() | 返回该对象的字符串 |
getClass().getName()+"@"+Integer.toHexString(hashCode());
1.getClass().getName()代表返回对象所属类的类名,即Animal
hashCode()代表返回该对象的哈希值
Integer.toHexString(hashCode())代表将对象的哈希值用十六进制表示
其中,hashCode()是Object类中定义的一个方法,这个方法将对象的内存地址进行哈希运算,返回一个int类型的哈希值
匿名内部类
java中内部类可以分为成员内部类,方法内部类和匿名内部类
匿名内部类就是没有名字的内部类
interface Animal{
void shout();
}
public class Example18{
public static void main(String[] args){
class Cat implements Animal{
public void shout(){
System.out.println("喵喵。。。");
}
}
animalShout(new Cat());
}
public static void animalShout(Animal an){
an.shout();
}
匿名内部类的格式:
new 父类(参数列表)或父接口(){
}
interface Animal{
void shout();
}
public class Example19{
public static void main(String[] args){
animalShout(new Animal(){
public void shout(){
System.out.println("喵喵。。。");
}
});
}
public static void animalShout(Animal an)
an.shout();
}
}
匿名内部类的格式:
animalShout(new Animal(){});
如下:
animalShout(new Animal(){
public void shout(){
System.out.println("喵喵。。。");
}
});