🎊前言:
俗话说:“千里之行始于足下”,今天是Java从零学起系列的第七篇,万事开头难,要坚持哦!本篇文章主要是Java程序面向对象的知识。
目录
活动地址:CSDN21天学习挑战赛
被其它类继承的类;
去继承的类;
类与类之间存在着相同的部分,比如:成员变量或者是方法;继承的有点显而易见,增强了代码的复用性,提高了开发效率,降低了程序产生的错误的可能性。子类在继承父类时需要使用extends关键字,语法格式如下:
class 父类名{
............
}
class 子类名 extends 父类名{
.............
}
- public class Animal {
- private String name;
- private int id;
- public Animal(String myName, int myid) {
- name = myName;
- id = myid;
- }
- public void eat(){
- System.out.println(name+"正在吃");
- }
- public void sleep(){
- System.out.println(name+"正在睡");
- }
- public void introduction() {
- System.out.println("大家好!我是" + id + "号" + name + ".");
- }
- }
- public class Penguin extends Animal {
- public Penguin(String myName, int myid) {
- super(myName, myid);
- }
- }
注:子类除了继承父类的成员变量和方法,还可以有自己的私有成员变量和方法
- public class Mouse extends Animal {
- private int age;
-
- public int getAge() {
- return age;
- }
-
- public void setAge(int age) {
- this.age = age;
- }
-
- public Mouse(String myName, int myid) {
- super(myName, myid);
- }
- public void Age() {
- System.out.println("我今年"+getAge()+"了!");
- }
- }
在继承关系中,子类会自动继承父类中定义的方法,但有时在子类中需要对继承的方法进行一些修改,即对父类方法进行重写。在子类中重写的方法需要和父类被重写的方法具有相同的方法名、参数列表和返回值类型,且在子类重写的方法不能比父类方法更加严格的访问权限。
- //父类
- class Animal {
- void shout() {
- // TODO Auto-generated method stub
- System.out.println("动物发出叫声");
- }
- }
- class Dog extends Animal{
- //重写父类中的shout方法
- void shout() {
- System.out.println("汪汪汪......");
- }
- }
- //主类
- public class Main{
- public static void main(String[] args) {
- Dog dog=new Dog();//创建Dog类实例对象
- dog.shout(); //调用Dog类中重写的shout方法
- }
- }
- /*运行结果
- 汪汪汪......
- */
super关键字:我们可以通过super关键字来实现对父类成员的访问,用来引用当前对象的父类。语法格式如下:
super.成员变量
super.成员方法(参数1,参数2...)
- //父类
- class Animal {
- private String name;
- private int age;
- public Animal(String name,int age) {
- this.name=name;
- this.age=age;
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public int getAge() {
- return age;
- }
-
- public void setAge(int age) {
- this.age = age;
- }
-
- public String info() {
- return "名字:"+this.getName()+",年龄:"+this.getAge();
- }
- }
- class Dog extends Animal{
- private String color;
- public Dog(String name,int age,String color) {
- super(name, age);
- this.setColor(color);
- }
-
- public String getColor() {
- return color;
- }
-
- public void setColor(String color) {
- this.color = color;
- }
-
- //重写父类中的info方法
- public String info() {
- return super.info()+",颜色:"+this.getColor();
- }
- }
- //主类
- public class Main{
- public static void main(String[] args) {
- Dog dog=new Dog("柴犬",2,"黄色");//创建Dog类实例对象
- System.out.println(dog.info()); //调用Dog类中重写的shout方法
- }
- }
- /*运行结果
- 名字:柴犬,年龄:2,颜色:黄色
- */