【Java 基础篇】【第四课】初识类

看看Java中如何定义一个类,然后用来调用的,这个比较简单,直接看代码吧。

我发现的类和C++不一样的地方:

1.Java中类定义大括号后没有分号;

2.好像没有 public、private等关键字(我也是跟着一个教程学的,至少刚开始没看到,补充一下后来知道有了写法是,直接 private int num; 这样在变量类型的前面直接加)

3.感觉类里面直接就写函数的实现了,不像C++在.h中进行定义,在.cpp中进行实现。

一个最基本的类,被外部调用:

 1 package a.b;
 2 
 3 class Human
 4 {
 5     void breath()
 6     {
 7         System.out.println("hu.....hu.....");
 8     }
 9     int height;
10 }
11 
12 public class four 
13 {
14     public static void main(String[] args) 
15     {
16         Human allen = new Human();
17         allen.breath();
18         System.out.println(allen.height);
19     }
20 
21 }

运行结果为:

hu.....hu.....
0

接受外部参数、返回类成员的例子:

 1 package a.b;
 2 
 3 class Human
 4 {
 5     void breath()
 6     {
 7         System.out.println("hu.....hu.....");
 8     }
 9     
10     void AddHeight(int num)
11     {
12         height = height +num;
13         for (int i = 0; i < num; i++)
14         {
15             breath();
16         }
17     }
18     
19     int GetHight()
20     {
21         return height;
22     }
23   
24     // 默认给成员变量初始化
25     private int height = 10;
26 }
27 
28 public class four 
29 {
30     public static void main(String[] args) 
31     {
32         Human allen = new Human();
33         allen.AddHeight(5);
34         System.out.println(allen.GetHight());
35     }
36 }

运行结果为:
hu.....hu.....
hu.....hu.....
hu.....hu.....
hu.....hu.....
hu.....hu.....
15

原文地址:https://www.cnblogs.com/by-dream/p/3958574.html