JAVA类与对象(五)----对象的生成、使用

时间:2024-01-05 18:52:38

对象的生成

创建一个对象包括对象的声明、实例化、初始化三部分。

1.声明-----类名对象名

  声明并不是为对象分配内存空间,而只是分配一个引用空间。对象的引用类似于指针,是32位的地址空间,它的值指向一个中间的数据结构,它储存有关数据类型的信息以及当前对象所在的堆的地址,而对于对象所在的实际的内存地址是不可操作的,这就保证了安全性。

2.实例化

  运算符new为对象分配内存空间,它调用对象的构造方法,返回引用。一个类的不同对象分别占用着不同的内存空间。

3.生成

  执行构造方法进行初始化,根据参数不同调用相应的构造方法。

注意:如果类中没有构造方法,系统会自动调用默认的构造方法。默认的构造方法是无参数的。如果类中定义了构造方法,则必须使用类中定义的构造方法,否则会出错!

例:

class Student{
float height,weight;
String head,ear,hand,foot,mouth;
Student()
{
height=0;
weight=0;
head="myhead";
ear="myear";
hand="myhead";
foot="myfoot";
mouth="mymouth";
System.out.println("new Student ok!!!");
}
} public class Man{
public static void main(String args[]){
Student zhangsan=new Student();
}
}

aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAANgAAAAnCAIAAADihhF2AAAC2klEQVR4nO2bXXKDMAyEOXQukJtxqBygD50yrq2flWxAGfZ76CRCSGt5IWmTbp/3ayPkdnJG3Pd9tRDybD7v1z6AnKilJUpNktN/C662K/W347p/dL93xE4BIsjOuXhJCf134c7tSvGdES/rK9AZEVdDI6apI+/LjKipNKTTiDZFFFY0ovEuYYkRx/r2exRDj9turGnUH8/tDkV17hKuZm3JdkdEj0FXB+kbbYGSfmm2k8dVLXlstNN2vY1oyxTj0TriY3uwbvCauW3/V2fXjLZAmTGikW/EQ4MDrzz8khCDoBFtAVEjhkZ36tzan3hf7ZQk4m/NOPg024tvzMTzQzK0Q8ZA9z/AFqJO14i44AvmptU31iU+nSL95xs72d7p8RCej2tIyJupgxvRXpFbs326ZG624QoZ8bg4RKI7LV7EWsRubWtIyDs6jn3tOl2+YUR3OVqd8+ZmGFFblyYgD/LJyrwR2yL4Hmv5YqbWETmqKWkFuMPpHhhBm1HDqXPrlgmuK7QiiCVfemjX00a+DmSnz+77paObZa0RF18lQxeR87qsrVytaS34NTBSAhqRlIBGJCWgEUkJaERSgsuMeOqvujXRlhmNP4JrjHjG3+duN7QrgEYMUMGI6Q2Y3Ln5jacRl3GLEUNHzzhxyeluBRoxwPFZ86Z8eji+sevyN+xVUkwQ3zh21cSno1RXJ1LE1i/W6Y66S07EH0H7rwJHsJ1vm3zsq5spou36GNR2NBEX1Wp9Ndy+4Lpy8Udgfw0M3IDQBF3bzegB41pfDbv+KsPRiM4dpaVNOCLRCbqGyN35NJ1436jgrh3JE7ojdgm4C6OGmLzzpftquH3pxVlyL81GjghoCLGmdodD7nzRvhrIie7llI4/gvYb2r8R7Wl6F7siYr5Y/whq8myd9lOtL7IETYk2orFUKP4I+FkzKQGNSEpAI5IS0IikBDQiKQGNSEpAI5IS0IikAj8rw8CalPG5bgAAAABJRU5ErkJggg==" alt="" />

对象的使用

  对象不仅可以改变自己变量的状态,而且还拥有使用创建它的那个类中的方法的能力。对象通过这些方法可以产生一定的行为,通过运算符“.”可以实现对变量和方法的访问。而变量和方法通过设置的权限来限制其他对象对自身的访问。

1.对象调用自己的变量

对象名.变量名

2.对象调用自己的方法

 对象名.方法名(参数);

例:

class Person{
float height,weight;
String head,ear,hand,foot,mouth;
Person()
{
height=175;
weight=70;
head="myhead";
ear="myear";
hand="myhead";
foot="myfoot";
mouth="mymouth";
System.out.println("new Student ok!!!");
}
void speak(String s)
{
System.out.println("say:"+s);
}
} public class Human{
public static void main(String args[]){
Person zhangsan=new Person();
zhangsan.speak("hello java!!!");
Person lisi=new Person();
lisi.ear="大耳朵";
lisi.speak("I am studying java!!!");
}
}

aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQQAAABjCAIAAADy7OkLAAAGe0lEQVR4nO2dMXLkOAxFddM9296kL7Chw4mcOHCVXT7BBsNRaUjgAyAhker+L5IgEgAh/JamWx5tPz8/39/fX19fn5+fHx8f7+/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