ajie; //声明对象 zhubajie=new XiyoujiRenwu(); //为对象分配内存,使用new 运算符和默认的构造方法 System.out.println(s);
例子2
class Point { int x,y; Point(int a,int b) { } } public class A { public static void main(String args[]) { Point p1,p2; p1=new Point(10,10); p2=new Point(23,35); } } //声明对象p1和p2 //为对象分配内存,使用 new 和类中的构造方法 //为对象分配内存,使用 new 和类中的构造方法 x=a; y=b;
例子3
class XiyoujiRenwu { float height,weight; String head, ear,hand,foot,mouth; void speak(String s) { head="歪着头"; System.out.println(s); 9
} } class Example4_3 { public static void main(String args[]) { XiyoujiRenwu zhubajie=new zhubajie,sunwukong;//声明对象 XiyoujiRenwu(); //为对象分配内存 //对象给自己的变量赋值
sunwukong=new XiyoujiRenwu(); zhubajie.height=1.80f; zhubajie.head="大头"; zhubajie.ear="一双大耳朵"; sunwukong.height=1.62f; sunwukong.weight=1000f; sunwukong.head="绣发飘飘"; System.out.println("zhubajie的身高:"+zhubajie.height); System.out.println("zhubajie的头:"+zhubajie.head); System.out.println("sunwukong的重量:"+sunwukong.weight); System.out.println("sunwukong的头:"+sunwukong.head); zhubajie.speak("俺老猪我想娶媳妇"); //对象调用方法 System.out.println("zhubajie现在的头:"+zhubajie.head); sunwukong.speak("老孙我重1000斤,我想骗八戒背我"); //对象调用方法 System.out.println("sunwukong现在的头:"+sunwukong.head); } } //对象给自己的变量赋值
例子4
class 梯形 { float 上底,下底,高,面积; 梯形(float x,float y,float h) { 上底=x; 下底=y; 高=h; } float 计算面积() { } void 修改高(float height) { } float 获取高() { } } 10 return 高; 高=height; 面积=(上底+下底)*高/2.0f; return 面积;
public class Example4_4 { public static void main(String args[]) { 梯形 laderOne=new 梯形(12.0f,3.5f,50),laderTwo=new 梯形(2.67f,3.0f,10); System.out.println("laderOne的高是:"+laderOne.获取高()); System.out.println("laderTwo的高是:"+laderTwo.获取高()); System.out.println("laderOne的面积是:"+laderOne.计算面积()); System.out.println("laderTwo的面积是:"+laderTwo.计算面积()); laderOne.修改高(10); float h=laderOne.获取高(); laderTwo.修改高(h*2); System.out.println("laderOne现在的高是:"+laderOne.获取高()); System.out.println("laderTwo现在的高是:"+laderTwo.获取高()); System.out.println("laderOne现在的面积是:"+laderOne.计算面积()); System.out.println("laderTwo现在的面积是:"+laderTwo.计算面积()); } }
例子5
class People { String face; void setFace(String s) { } } class A { void f(int x,double y,People p) { x=x+1; y=y+1; p.setFace("笑脸"); System.out.println("参数x和y的值分别是:"+x+","+y); System.out.println("参数对象p的face是:"+p.face); } } public class Example4_5 { public static void main(String args[]) { int x=100; double y=100.88; People zhang=new People(); zhang.setFace("很严肃的样子"); A a=new A(); a.f(x,y,zhang); System.out.println("main方法中x和y的值仍然分别是:"+x+","+y); System.out.println("main方法中对象zhang的face是:"+zhang.face); 11 face=s;
} }
例子6
class 圆 { double 半径; 圆(double r) { } double 计算面积() { } voi