Java中构造函数和普通函数的区别

1.构造函数(Constructor)定义格式:
访问控制符(public等)+方法名(必须和类名一致)+参数(可有可无)
2.功能:主要再构建对象时对对象进行初始化,必须与new运算符一起使用。
3.区别:
(1)构造函数没有返回值,也不能用void来修饰。普通方法必须有返回值。
(2)在命名规则上,构造函数一般是首字母大写,普通函数遵照小驼峰式命名法。
(3)构造函数不能被直接调用,必须通过new运算符在创建对象时才会自动调用;而一般的方法是在程序执行到它的时候被调用的;
(4)构造函数在new的时候自动调用优先级高于普通方法

blic class Math {
 private int count;
 //构造函数
 
/**修饰符 函数名(形式参数){
*         函数体
*    }
*/

 public Math() {
  System.out.println("此为构造方法");
 }
 
 //普遍方法
 public void math() {
  System.out.println("此为普通方法");
 }
 
 public int add() {
  count++;
  return count;
 }
 public int getCount() {
  return count;
 }
 public void setCount(int count){
 this.count = count;
 }
 }
 //测试函数
 public class Text {
 public static void main(String[] args) {
  //初始化a
  Math a = new Math();
  //调用普通方法
     a.math(); 
     int count = a.getCount();
     System.out.println(count);
     a.add();
     int count1 = a.getCount();
     System.out.println(count1);
     }
     }

测试结果:
在这里插入图片描述

发布了7 篇原创文章 · 获赞 6 · 访问量 457

猜你喜欢

转载自blog.csdn.net/qq_44454898/article/details/90737157