继承相关笔记

关于procted、abstract

要求两个变量可以被同一个包中的类以及该类的所有子类访问到

public abstract class Shapes {
	 protected int width;
	 protected int height;
	 
	 public Shapes(int width,int height) {
		 this.width = width;
		 this.height = height;	 
	 }
	 
	 public abstract double getArea();
	 
	 public abstract double getPerimeter();

}

首先abstract定义抽象类Shapes。后两个语句getArea()、getP..()为抽象方法,分号结束。抽象类是不能被实例化的类,它主要用于被继承。而抽象方法是没有实际实现的方法,它需要在具体的子类中被重写并给出具体的实现。如:

public double getArea() {

		return width*height;
	}

	public double getPerimeter() {
		
		return 2*(width + height);
	}

此处return值的成功返回在于父类procted声明变量!!!

完整子类代码:

import oop.core.base.Shapes;

public class Square extends Shapes{

	public Square(int width, int height) {
		super(width, height);
		
	}

	public double getArea() {

		return width*height;
	}

	public double getPerimeter() {
		
		return 2*(width + height);
	}

super

super关键字:我们可以通过super关键字来实现对父类成员的访问,用来引用当前对象的父类。

this关键字:指向自己的引用。

class Animal {
  void eat() {
    System.out.println("animal : eat");
  }
}
 
class Dog extends Animal {
  void eat() {
    System.out.println("dog : eat");
  }
  void eatTest() {
    this.eat();   // this 调用自己的方法
    super.eat();  // super 调用父类方法
  }
}
 
public class Test {
  public static void main(String[] args) {
    Animal a = new Animal();
    a.eat();
    Dog d = new Dog();
    d.eatTest();
  }
}

输出结果为:

animal : eat
dog : eat
animal : eat
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值