Java的代码结构

阅读量: 1003 编辑

学到这里,基本上一个类的代码结构我们基本上就掌握了,我们常写的程序代码包括了这些知识点;

一、类文件包含如下的这些元素:

1、package:类所在的包

2、import:引入其他的包

3、类的定义:

  • 属性定义(包括访问权限)

  • 构造器定义

  • 方法定义

  • setter & getter 方法

  • static 修饰的属性或方法

  • this 关键字

  • 主函数

  • new 语法

对于这些知识,多写程序、多练习就可以很快掌握;

二、编程实战

代码的详细解读,可以参考视频教程

package com.qicong.zj.c10;//包package

/**
 * User: 祁大聪
 */
public class Person { // 类名
	
    // 属性
    private String name;
    private int age;
    private int height;
    private double money;

	 // 静态属性
    private static String school;

	 // 构造器
    public Person(){

    }

	 // 构造器
    public Person(String name){
        this.name = name;
    }

	 // 方法
    public String getPeopleInfo(){
        return name + " , " + age + " , " + school;
    }

    // 静态方法
    public static String getStaticSchool(){
        return school;
    }

    // 主函数(方法)
    public static void main(String[] args) {
		Person p = new Person();//实例化
        p.name = "胡歌";//调用
    }


    // 用于访问私有属性的 setter & getter 方法
    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 int getHeight() {
        return height;
    }

    public void setHeight(int height) {
        this.height = height;
    }

    public double getMoney() {
        return money;
    }

    public void setMoney(double money) {
        this.money = money;
    }

    public static String getSchool() {
        return school;
    }

    public void setSchool(String school) {
        this.school = school;
    }
}


爱码岛编程公众号
试卷资料
爱码岛编程小程序
在线刷题
苏ICP备13052010号
©2023 南京匠成信息科技有限公司