keyword:extends
继承,顾名思义就是子类继承父类的中的一切,简单点可以理解为把父类放在子类中。(比如鸟的爸爸(父类)会飞,那么鸟儿子(子类)就继承了鸟爸爸的飞的能力,它就也会飞;而乌龟儿子(子类)不是鸟爸爸的儿子,自然他就不能继承鸟爸爸(父类)飞的能力,它就不会飞。)
一.单个继承。
(只有儿子继承父亲并且只有一个儿子)
1.有参构造方法的继承。
package b;
import java.util.*;
class father{
public int a,b;
public father(int x,int y) {
this.a=x;
this.b=y;
}
}
class son extends father{
public son(int x, int y) {
super(x, y);
}//这一步不能少,少了会报错。
int s=super.a+super.b;//可以不写super,但是养成良好的习惯,还是把super写上。
void print() {
System.out.println("num1 = "+super.a);
System.out.println("num2 = "+super.b);
System.out.println("sum = "+s);
}
}
public class Person {
public static void main(String args[]) {
son s=new son(10,20);
s.print();
}
}
/*输出结果:
num1 = 10
num2 = 20
sum = 30
*/
1.无参构造方法的继承。
package b;
import java.util.*;
class father{
public int a=0,b=0;
void insert(int x,int y) {
this.a=x;//this可以不写,但是为了养成良好的习惯。
this.b=y;
}
}
class son extends father{
int s;
void print() {
s=super.a+super.b;//不可放在放在int s的后面,否则s=0,因为int为不可变变量。
//可以不写super,但是为了养成良好的习惯,还是把super写上。
System.out.println("num1 = "+super.a);
System.out.println("num2 = "+super.b);
System.out.println("sum = "+s);
}
}
public class Person {
public static void main(String args[]) {
son s=new son();
s.insert(10, 20);
s.print();
}
}
/*输出结果:
num1 = 10
num2 = 20
sum = 30
*/
二.多重继承。
多重继承和单个继承方法是相同的,只不过,他不只儿子继承父亲,他还有孙子继承儿子,曾孙继承孙子……。
package b;
import java.util.*;
class father{
int a=10;
void print_a() {
System.out.println("a = "+a);
}
}
class son extends father{
int b=20;
void print_b() {
System.out.println("b = "+b);
}
}
class grandson extends son{
int c=super.a+super.b;//可以不写super,但是为了养成良好的习惯,还是把super写上。
void print_c() {
System.out.println("c = "+c);
}
}
public class Person {
public static void main(String args[]) {
grandson s=new grandson();
s.print_a();
s.print_b();
s.print_c();
}
}
/*输出结果:
a = 10
b = 20
c = 30
*/
三.层继承。
层继承和单个继承的方法也是相同的,但是一个父亲不一定只生一个孩子,他可能有2个,3个……。
package b;
import java.util.*;
class father{
void print_1() {
System.out.println("my father class is 'father'");
}
}
class son1 extends father{
void print_2() {
System.out.println("I am son1");
}
}
class son2 extends father{
void print_3() {
System.out.println("I am son2");
}
}
public class Person {
public static void main(String args[]) {
son1 s1=new son1();
son2 s2=new son2();
s1.print_1();
s1.print_2();
System.out.println("------------------------------");
s2.print_1();
s2.print_3();
}
}
/*输出结果:
my father class is 'father'
I am son1
------------------------------
my father class is 'father'
I am son2
*/