使用super调用父类的构造方法
class Student{
int number;
String name;
Student(){
}
Student(int number,String name){
this.number=number;
this.name=name;
System.out.println("我的名字是:"+name+"学号是:"+number);
}
}
class UniverStudent extends Student{
boolean 婚否;
UniverStudent(int number,String name,boolean b){
super(number,name);
婚否=b;
System.out.println("婚否="+婚否);
}
}
public class exam {
public static void main(String[] args) {
UniverStudent zhang =new UniverStudent(9901,"何晓林",false);
}
}
final关键字
class A{
final double PI=3.1415926; //PI常量
public double getArea(final double r){
//r=r+1; 非法,不允许对final变量进行更新操作
return PI*r*r;
}
public final void speak(){
System.out.println("您好,How' everything here?");
}
}
public class exam {
public static void main(String[] args) {
A a=new A();
System.out.println("面积:"+a.getArea(100));
a.speak();
}
}
对象的上转型对象
class 类人猿{
void crySpeak(String s){
System.out.println(s);
}
}
class People extends 类人猿{
void computer(int a,int b){
int c=a*b;
System.out.println(c);
}
void crySpeak(String s){
System.out.println("***"+s+"***");
}
}
public class exam {
public static void main(String[] args) {
类人猿 monkey;
People geng = new People();
monkey =geng;//monkey是People对象geng的上转型对象
monkey.crySpeak("I love this game");
//同等于geng.crySpeak("I love this game");
People people=(People)monkey; //把上转型对象强置转化为子类的对象
people.computer(10, 10);
}
}
继承与多态
class 动物{
void cry(){
}
}
class 狗 extends 动物{
void cry(){
System.out.println("汪汪汪....");
}
}
class 猫 extends 动物{
void cry(){
System.out.println("喵喵喵....");
}
}
public class exam {
public static void main(String[] args) {
动物 animal;
animal=new 狗();
animal.cry();
animal=new 猫();
animal.cry();
}
}
abstract类和abstract方法
abstract class GirlFriend{ //抽象类,封装了两个行为标准
abstract void speak();
abstract void cooking();
}
class ChinaGirlFriend extends GirlFriend{
void speak(){
System.out.println("你好");
}
void cooking(){
System.out.println("水煮鱼");
}
}
class AmericanGirlFriend extends GirlFriend{
void speak(){
System.out.println("Hello");
}
void cooking(){
System.out.println("roast beef");
}
}
class Boy{
GirlFriend friend;
void setGirlfriend(GirlFriend f){
friend=f;
}
void showGirlFriend(){
friend.speak();
friend.cooking();
}
}
public class exam {
public static void main(String[] args) {
GirlFriend girl=new ChinaGirlFriend(); //girl是上转型对象
Boy boy=new Boy();
boy.setGirlfriend(girl);
boy.showGirlFriend();
girl=new AmericanGirlFriend(); //girl是上转型对象
boy.setGirlfriend(girl);
boy.showGirlFriend();
}
}