哈喽哟,上一弹讲述了接口,这一讲将要讲述继承,这些都是和面向对象一样非常重要的内容,Java也就是由这些内容构建起来的。这一弹主要的内容如下:
(0)继承语法
下面就通过具体的操作代码进行说明:
package com.csdn.extend;
//继承可以继承除private属性和方法外的所有属性和方法
//object是java的顶级父类
public class Demo11 {
public static void main(String[] args) {
Dog dog = new Dog();
System.out.println("dog.age");
System.out.println("dog.color");
System.out.println("dog.name");
//System.out.println("dog.privateStr");
dog.eat();dog.m2();dog.m3();
//dog.m1();
}
}
class Animal{
private String privateStr = "privateStr";
String name = "huahua";
protected int age = 4;
public String color = "黑色";
public void eat() {
System.out.println("eat...");
}
private void m1() {
System.out.println("m1");
}
protected void m2() {
System.out.println("m2");
}
void m3() {
System.out.println("m3");
}
}
class Dog extends Animal{
}
(1)方法覆盖
同样代码给出如下:
package com.csdn.extend;
//继承可以继承除private属性和方法外的所有属性和方法
//object是java的顶级父类
public class Demo11 {
public static void main(String[] args) {
Dog dog = new Dog();
System.out.println("dog.age");
System.out.println("dog.color");
System.out.println("dog.name");
//System.out.println("dog.privateStr");
dog.eat();dog.m2();dog.m3();
//dog.m1();
}
}
class Animal{
private String privateStr = "privateStr";
String name = "huahua";
protected int age = 4;
public String color = "黑色";
public void eat() {
System.out.println("eat...");
}
private void m1() {
System.out.println("m1");
}
protected void m2() {
System.out.println("m2");
}
void m3() {
System.out.println("m3");
}
}
//子类覆盖父类
class Dog extends Animal{
@Override
public void eat() {
super.eat();
System.out.println("Dog eat...");
}
}
(2)方法重载(不是继承中的内容,主要是来和方法覆盖进行并向讲述),重载和继承是非常相似的内容,虽然相似但是也有不同点,那就是覆盖是要有继承关系才能覆盖,而重载是只要在一个类里面就可以进行重载。
package com.csdn.extend;
//继承可以继承除private属性和方法外的所有属性和方法
//object是java的顶级父类
public class Demo11 {
public static void main(String[] args) {
Dog dog = new Dog();
System.out.println("dog.age");
System.out.println("dog.color");
System.out.println("dog.name");
//System.out.println("dog.privateStr");
dog.eat();dog.m2();dog.m3();
//dog.m1();
}
}
//方法重载 方法名相同,参数的个数或者类型不同(方法重载是在一个类里面)
class Person{
String name;
int age;
//构造方法重载
public Person() {
}
public Person(String name) {
this.name = name;
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public void eat() {
System.out.println("eat...");
}
public void eat(String food) {
System.out.println("eat" + food);
}
}
class Animal{
private String privateStr = "privateStr";
String name = "huahua";
protected int age = 4;
public String color = "黑色";
public void eat() {
System.out.println("eat...");
}
private void m1() {
System.out.println("m1");
}
protected void m2() {
System.out.println("m2");
}
void m3() {
System.out.println("m3");
}
}
//子类覆盖父类(在继承关系里面才会有覆盖)
//super 是指父类的引用
//this 是当前对象
class Dog extends Animal{
@Override
public void eat() {
super.eat();
System.out.println("Dog eat...");
}
}
(3)super关键字
super其实就是指父类,在继承里面,子类覆盖父类就会出现super关键字。