Java类来自网页


/**
* 这个类作为Dog的父类
* @author
* @date 2018年1月22日上午9:40:45
* java所有的类默认继承Object,
* 一个类的父类包括直接和间接的父类。
* 一个类只能有一个直接父类,一个类不能同时继承多个类,在java只支持单继承,不支持多继承,java中是支持多重继承。
* 子类继承父类,只能使用非private修饰的成员变量以及方法
*/
public class Animal extends Object{
String name;
private int age;
static String sex="雌";
static{
System.out.println("this is static code ,Anmian sex is "+sex);
}
{
System.out.println("this is not static code");
}
public Animal() {
System.out.println("this is Animal ");
}
public void run(){
System.out.println("Animal is running");
}
private void sleep(){
System.out.println(" Animal is sleeping ");
}
}


/**
* 这个类作为Aninal的子类,可以是使用Animal类中的属性
*
* @author
* @date 2018年1月22日上午9:41:09 Dog TestDemo1
*/
public class Dog extends Animal {
/*
* 有父子类的情况:
* (1)父类的static变量和static初始化块
* (2)子类的static变量和static初始化块
* (3)父类的实例变量、初始化块
* (4)父类的构造方法
* (5)子类的实例变量、初始化块
* (6)子类构造方法
*/

String voice;
static String belongPeson = "小明";

static {
System.out.println("this is Dog static code belongPeson is" + belongPeson);
}

{
System.out.println("this is Dog not static code");
}

public Dog() {
super();
System.out.println("this is Dog");
}

public Dog(String voice) {
this.voice = voice;
System.out.println("这是Dog的有参构造方法");
}

public void voice() {
System.out.println("this is Dog voice");
}
}


/**
*
* @author
* @date 2018年1月22日上午10:03:20
* Courser 这个类是Dog的子类,Dog又是Animal的子类,所以Courser也是Animal间接子类,
* Courser可以直接用Animal和Dog中的属性和方法
* TestDemo1
*/
public class Courser extends Dog{
public Courser() {
// 在子类的构造方法中可以默认通过super()来调用父类的构造方法,而且super()必须放到第一行
// 也就是在调用子类构造方法时,会先执行父类的构造方法
// 使用super需要注意的地方
// 1.只能在子类的构造方法中使用super(参数)来调用父类构造方法
// 2.调用父类构造方法时,只能使用super(…)
// 3.super()必须放到第一行
// 4.如果子类中没有调用父类构造,会默认调用无参数的super()
// 5.子类调用父有参类的构造方法时,super()中的参数类型一定要和父类构造方法中参数类型保持一致。
// super();

super("旺旺");
int age=10;
System.out.println("this is Courser");

}
static String desc="抓兔子";
double height=100;
static{
System.out.println("this is Courser static code desc is "+desc);
}
{
System.out.println("this is Courser not static code");
}
public void voice(){
// 子类可以直接通过super调用父类的方法和属性

super.voice();
super.name="tom";
}
//在子类的静态方法中是不能通过super调用父类的方法
public static void sleep(){

}
public static void main(String[] args) {
Courser c = new Courser();
}
}
————————————————
版权声明:本文为CSDN博主「专业萌新不给就送」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/Interest_Soul/article/details/79129329

猜你喜欢

转载自www.cnblogs.com/dshc/p/11977998.html
今日推荐