java怎么封装接口
答案:2 悬赏:20 手机版
解决时间 2021-01-28 13:22
- 提问者网友:富士山上尢
- 2021-01-28 06:04
java怎么封装接口
最佳答案
- 五星知识达人网友:执傲
- 2021-01-28 06:49
我们先来封装以前定义的Human类:
public class Test
{
public static void main(String[] args)
{
Human aPerson = new Human(160);
System.out.println(aPerson.getHeight());
aPerson.growHeight(170);
System.out.println(aPerson.getHeight());
aPerson.repeatBreath(100);
}
}
class Human
{
public Human(int h)
{
this.height = h;
System.out.println("I'm born");
}
public int getHeight()
{
return this.height;
}
public void growHeight(int h)
{
this.height = this.height + h;
}
private void breath()
{
System.out.println("hu...hu...");
}
public void repeatBreath(int rep)
{
int i;
for(i = 0; i < rep; i++) {
this.breath();
}
}
private int height; // encapsulated, for internal use
}
public class Test
{
public static void main(String[] args)
{
Human aPerson = new Human(160);
System.out.println(aPerson.getHeight());
aPerson.growHeight(170);
System.out.println(aPerson.getHeight());
aPerson.repeatBreath(100);
}
}
class Human
{
public Human(int h)
{
this.height = h;
System.out.println("I'm born");
}
public int getHeight()
{
return this.height;
}
public void growHeight(int h)
{
this.height = this.height + h;
}
private void breath()
{
System.out.println("hu...hu...");
}
public void repeatBreath(int rep)
{
int i;
for(i = 0; i < rep; i++) {
this.breath();
}
}
private int height; // encapsulated, for internal use
}
全部回答
- 1楼网友:想偏头吻你
- 2021-01-28 07:00
get和set都是类定义的方法,你的变量是private型的,就是私有类型,其他类都不能访问私有类型的变量,所以要在这个类内部设个能访问这些变量的方法,就是get和set,别个类要访问这两个私有变量的话,就可以通过这些方法来访问了。
如果有个test类
public class test {
public static void main(string[] args) {
man m = new man();
m.age = 12;
m.name = "ddaf";这两个写法都是错了,因为不能直接访问age,和name;
要写成这样 m.setage(12);m.setname('dadfa');这样才对;
}
}
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯