JAVA基础(56)---抽象类

版权声明:如需转载请标明出处 https://blog.csdn.net/yj201711/article/details/84142962

抽象类

面向对象的程序设计:类的设计是从抽象到具体,在抽象的过程中,又是从具体到抽象

abstarct:修饰类,使用该关键字修饰的类就是抽象类

                 修饰方法,该方法就是抽象方法

特点

  1. 不能实例化(不能创建对象)
  2. 存在构造方法:就是为了创建子类对象来使用的(就是为了让子类中能够访问父类中的成员)
  3. 抽象类中不一定要有抽象方法:就是要使用该类中的成员属性和方法,必须继承该类
  4. 存在抽象方法的类,必须是抽象类
  5. 如果子类中没有重写抽象类中的所有的抽象方法,那么该子类也必须是抽象的,直到子类重写了所有的抽象方法

意义

           是用来被继承的

抽象类的构成

成员变量、成员方法、构造方法、常量、静态变量、构造代码块、静态代码块

抽象方法和具体的方法之间的区别:抽象方法没有方法体只有方法的声明,以分号结尾(就是说方法后面没有大括号)

抽象方法存在的意义:是用来被重写的

抽象类的子类必须去实现抽象类中的所有的抽象方法

关于抽象类中的几个小问题:

  • 抽象方法能不能使用private修饰?不能。因为  private  修饰的方法不能被继承
  • 抽象的方法或类,能不能使用final修饰?不能。因为  final  修饰的类不能被继承, final  修饰的方法不能被重写
  • 抽象方法能不能使用static修饰?不能。因为使用   static 修饰的方法不能被重写

   

public abstract class Animal {
	private String name;
	private int age;
	final int LEG = 4;
	static  int num = 10;
	{
		System.out.println("Animal的构造代码块....");
	}
	static {
		
		System.out.println("Animal的静态代码块....");
	}
	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 Animal() {
		System.out.println("Animal 的无参构造方法...");
	}
	public abstract void showInfo() ;
	
	public  abstract void testMethod();
}
public class Dog extends Animal{
	
	public Dog() {
		this.setName("旺财");
		this.setAge(2);
	}
	
	
	public void showInfo() {
		System.out.println(this.getName()+"---"+this.getAge()+"--"+ this.LEG + "--" + num);
		
	}


	@Override
	public void testMethod() {
		// TODO Auto-generated method stub
		
	}
	
}
import org.lanqiao.abstarct.demo.Animal;
import org.lanqiao.abstarct.demo.Dog;

public class AbstractTest {
	public static void main(String[] args) {
		Animal a = new Dog();
		a.showInfo();
	}
}


        
        
 

扫描二维码关注公众号,回复: 4131378 查看本文章

猜你喜欢

转载自blog.csdn.net/yj201711/article/details/84142962
今日推荐