zoukankan      html  css  js  c++  java
  • 面向对象思想,简单实例

    下面有一行代码,作用是求1-50之间偶数的和

    public class Mianxiangduixiang {
        public static void main(String[] args) {
            int sum=0;
            for(int i=0;i<=50;i++,i++){
                sum+=i;
            }
            System.out.println(sum);
        }
    }

    现为了实现让主方法调用方法来解题,引入面向对象思想;

    首先在主类外面编写一个类Func;

    并在类中编写一个子方法func1,返回值为int型

    然后将主方法中求1-50的方法放入子方法中;

    此时在子方法中不输出,而是将结果返回到主方法中,由主方法来实现

    class Func{
        public int func1(){
            int sum=0;
            for(int i=0;i<=50;i++,i++){
                sum+=i;
            }
            return sum;
        }
        
    }

    再主方法中使用new语句

    输出结果

    class Func{
        public int func1(){
            int sum=0;
            for(int i=0;i<=50;i++,i++){
                sum+=i;
            }
            return sum;
        }
        
    }
    
    public class Mianxiangduixiang {
        public static void main(String[] args) {
            Func func=new Func();
            System.out.println(func.func1());
        }
    }

    如果在子方法int前面加上static,再主方法中就不需要使用new语句

    class Func{
        public static int func1(){
            int sum=0;
            for(int i=0;i<=50;i++,i++){
                sum+=i;
            }
            return sum;
        }
        
    }
    
    public class Mianxiangduixiang {
        public static void main(String[] args) {
            System.out.println(Func.func1());
        }
    }

    同样可以输出,如果不加static,也不使用new语句,程序就无法运行

    会报错

    Cannot make a static reference to the non-static method func1() from the type Func

    意为不能对非静态方法func1()静态引用类型功能。

  • 相关阅读:
    Pyspark 提交任务遇到的问题
    Python的 figure参数和 subplot子图绘制
    Python的 plot函数和绘图参数设置
    Python的散点图绘制 scatter
    Python的random操作
    python的浅复制与深复制
    Python的itertools.product 方法
    python的关联图绘制 --- pyecharts
    DVWA——Brute Force暴力破解
    DVWA——简介
  • 原文地址:https://www.cnblogs.com/FrankLiner/p/7538494.html
Copyright © 2011-2022 走看看