对于方法覆盖(因此可以实现运行时多态) 。
用于代码可重用性。
类: 类是具有共同属性的一组对象。它是用于创建对象的模板或蓝图。
子类: 子类是继承其他类的类。也称为派生类,扩展类或子类。
父类: : 超级类是子类从中继承要素的类。也称为基类或父类。
可重用性: 顾名思义,可重用性是一种机制,可帮助您在创建新类时重用现有类的字段和方法。您可以使用上一类中已定义的相同字段和方法。
class Subclass-name extends Superclass-name{
//methods and fields}
class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
Programmer salary is:40000.0
Bonus of programmer is:10000
class Animal{
void eat(){
System.out.println("eating...");
}
}
class Dog extends Animal{
void bark(){
System.out.println("barking...");
}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}
}
barking...
eating...
class Animal{
void eat(){
System.out.println("eating...");
}
}
class Dog extends Animal{
void bark(){
System.out.println("barking...");
}
}
class BabyDog extends Dog{
void weep(){
System.out.println("weeping...");
}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}
}
weeping...
barking...
eating...
class Animal{
void eat(){
System.out.println("eating...");
}
}
class Dog extends Animal{
void bark(){
System.out.println("barking...");
}
}
class Cat extends Animal{
void meow(){
System.out.println("meowing...");
}
}
class TestInheritance3{
public static void main(String args[]){
cat c=new Cat();
c.meow();
c.eat();
//c.bark();
//C.T.Error}
}
meowing...
eating...
class A{
void msg(){
System.out.println("Hello");
}
}
class B{
void msg(){
System.out.println("Welcome");
}
}
class C extends A,B{
//suppose if it were public static void main(String args[]){
C obj=new C();
obj.msg();
//Now which msg() method would be invoked?}
}
Compile Time Error