抽象类的基本概念------abstract

抽象类的概念:

包含一个抽象方法的类就称为抽象类。

抽象方法:只声明但未实现的方法称为抽象方法,使用abstract关键字声明。

抽象类的定义及使用规则:



abstract class A{	// 是定义了一个抽象类
	public static final String FLAG = "CHINA" ;	// 全局常量
	private String name = "XIAOWU" ;	// 定义一个普通的属性
	public void setName(String name){
		this.name = name ;
	}
	public String getName(){
		return this.name ;
	}
	public abstract void print() ;		// 定义抽象方法
};
抽象类的子类覆写抽象类中的抽象方法。
abstract class A{	// 是定义了一个抽象类
	public static final String FLAG = "CHINA" ;	// 全局常量
	private String name = "XIAOWU" ;	// 定义一个普通的属性
	public void setName(String name){
		this.name = name ;
	}
	public String getName(){
		return this.name ;
	}
	public abstract void print() ;		// 定义抽象方法
};
class B extends A{	// 继承抽象类,因为B是普通类,所以必须覆写全部抽象方法
	public void print(){
		System.out.println("FLAG = " + FLAG) ;
		System.out.println("姓名 = " + super.getName()) ;
	}
};
public class AbstractDemo02{
	public static void main(String args[]){
		B b = new B() ;
		b.print() ;
	}
};

抽象类的思考:



abstract class A{	// 是定义了一个抽象类
	public A(){
		System.out.println("A、抽象类中的构造方法。") ;
	}
};
class B extends A{	// 继承抽象类,因为B是普通类,所以必须覆写全部抽象方法
	public B(){
		super() ;
		System.out.println("B、子类中的构造方法。") ;
	}
};
public class AbstractDemo03{
	public static void main(String args[]){
		B b = new B() ;
	}
};

abstract class Person{
	private String name ;		// 定义name属性
	private int age ;			// 定义age属性
	public Person(String name,int age){
		this.name = name ;
		this.age = age ;
	}
	public void setName(String name){
		this.name = name ;
	}
	public void setAge(int age){
		this.age = age ;
	}
	public String getName(){
		return this.name ;
	}
	public int getAge(){
		return this.age ;
	}
	public abstract String getInfo() ;	// 抽象方法
};
class Student extends Person{
	private String school ;
	public Student(String name,int age,String school){
		super(name,age) ;	// 指定要调用抽象类中有两个参数的构造方法
		this.school = school ;
	}
	public void setSchool(String school){
		this.school = school ;
	}
	public String getSchool(){
		return this.school ;
	}
	public String getInfo(){
		return	"姓名:" + super.getName()  + 
				";年龄:" + super.getAge() + 
				";学校:" + this.getSchool() ;
	}
};
public class AbstractDemo04{
	public static void main(String args[]){
		Student stu = new Student("张三",30,"清华大学") ;
		System.out.println(stu.getInfo()) ;
	}
};


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值