zoukankan      html  css  js  c++  java
  • Java SE 第二十一讲----抽象类

    1.抽象类(abstract class):使用了abstract关键字修饰的类叫做抽象类,抽象类无法实例化,也就是说,不能new出来一个抽象类的对象。

    2.抽象方法(abstract method):使用了abstract关键字修饰的方法叫做抽象方法,有声明无实现(没有花括号 public abstract void method();)

      抽象方法需要定义在抽象类中。相对于抽象方法,之前所定义的方法叫做具体方法(有声明,有实现)。

    3.如果某个类是包含了抽象方法,那么这个类一定是抽象类。

    4.如果某个类是抽象类,那么该类可以包含具体方法(有声明有实现)。

    5.如果一个类中包含了抽象方法,那么这个类一定要声明成抽象类,也就是说,该类一定是抽象类,繁殖如果某个类是抽象类,那么该类就可以包含抽象方法跟具体方法。

    6.无论何种情况,只要一个类是抽象类,那么这个类就无法实例化。

    7.在子类继承父类(父类是个抽象类)的情况下,那么该子类必须要实现父类中所定义的所有的抽象方法,否则,该子类需要声明成一个abstract class

    报错内容:The type R must implement the inherited abstract method T.method()

    class R extends T
    {
    
        @Override
        public void method() {
            // TODO Auto-generated method stub
            
        }
        
    }
    这样就好了

    或者将R变成abstract类,但是就不能被实例化了

    实例如下:计算图形的面积

    package com.cl.abstracttest;
    
    public class Test2 {
        public static void main(String[] args) {
            Shape t = new Triangle(2,4);
            int area = t.computArea();
            System.out.println("Triangle:"+area);//三角形
            t = new Rectangle(10,10);
            area = t.computArea();
            System.out.println("Rectangle:"+area);//矩形
        }
    
    }
    
    
     abstract class Shape{
         public abstract int computArea();
         
    }
     
    class Triangle extends Shape{
        int width;
        int height;
        public Triangle(int width,int height){
            this.width  = width;
            this.height = height;
            
        }
    
        public int computArea() {
            
            return (width * height) / 2;
        }
        
    }
    
    class Rectangle extends Shape{
        int width;
        int height;
        public Rectangle(int width,int height){
            this.width  = width;
            this.height = height;
            
        }
        @Override
        public int computArea() {
            
            return width*height;
        }
        
    }
  • 相关阅读:
    go get golang.org被墙问题解决
    golang的cms
    一次composer错误使用引发的思考
    colly源码学习
    IdentityServer4 禁用 Consent screen page(权限确认页面)
    Visual Studio for Mac 初体验
    ASP.NET Core 简单实现七牛图片上传(FormData 和 Base64)
    ASP.NET Core 注入和获取 AppSettings 配置
    ASP.NET Core 使用 Hangfire 定时任务
    Repository 简化实现多条件查询
  • 原文地址:https://www.cnblogs.com/dieyaxianju/p/5138650.html
Copyright © 2011-2022 走看看