在Java中将类作为参数传递 [英] passing class as an argument in java
问题描述
嗨...
我试图通过类作为参数...
但是我面临问题,概念不清晰...
代码的东西
Hi...
i was trying to pass class as argument...
But i.m facing problem,concept not dot clear...
code stuff
/* Class Test*/
class Test{
int x,y;
Test(int x,int y){
this.x=x;
this.y=y;
}
void m3(){
System.out.println("Test's m4");
}
}
/*class Box*/
class Box
{
int w,h,d;
Box(int w,int h,int d){
this.w=w;
this.h=h;
this.d=d;
}
void m1(){
System.out.println("Box's m1");
}
}
/*sub class of Box*/
class BoxWt extends Box
{
int w,h,d,wt;
BoxWt(int w,int h,int d,int wt){
super(w,h,d);
this.wt=wt;
}
void m2(){
System.out.println("BoxWt's m2");
}
}
/*Figure Abstract class*/
abstract class Figure{
int x,y;
Figure(int x,int y){
this.x=x;
this.y=y;
}
abstract double area();
}
class Tri extends Figure
{
int x,y;
Tri(int x,int y){
super(x,y);
}
double area(){
return (0.5*x*y);
}
}
/*Class Hello*/
class Hello{
Test m4(Box z){
System.out.println("M4,myreturn type is test");
Box b=new Box(1,2,3);
return b;
}
/* Box m5(int x,int y,int z){
System.out.println("m5,my return type is Box");
return 1;
}*/
void m6(BoxWt z){
System.out.println("m6,....................");
}
BoxWt m7(int x,int y,int z,int wt){
BoxWt bw=new BoxWt(x,y,z,wt);
return bw;
}
}
/*main class*/
class ExDemo{
public static void main(String[] args){
Box b=new Box(1,2,3);
BoxWt bw=new BoxWt(4,5,6,7);
Test t=new Test(10,20);
Hello h=new Hello();
Figure f;
f=new Tri(30,40);
}
}
请帮我整理一下..
谢谢你..
Pls help me to sort out..
Thank u..
推荐答案
您的主体已经向您显示了如何做:
Your main already shows you what to do:
/*main class*/
class ExDemo{
public static void main(String[] args){
Box b=new Box(1,2,3);
BoxWt bw=new BoxWt(4,5,6,7);
Test t=new Test(10,20);
Hello h=new Hello();
Figure f;
f=new Tri(30,40);
}
}
您正在将int
-值传递给对象(*).
因此,如果您想将一个对象作为参数传递给另一个对象,请按照相同的方式进行操作!
You are passing int
-values to the objects(*).
SO if you want to pass an object as a argument to another object - do it the same way!
Box b=new Box(1,2,3);
Test t=new Test(b); // b was passed as an argument to the object Test.
您很快就会发现Test
必须能够处理类型为Box
的精子:
You will soon find out that Test
needs to be capable to handle the argmuent of type Box
:
class Test{
private Box oBox; // member variable in class Test
public Test(Box aBox){
this.oBox = aBox; // handover of argument to member variable which can now be used in class
}
}
作为参数的对象的最简单版本是setter.与之直接相反的是一个吸气剂,它返回一个Object:
}
The simplest version of a object as argument is a setter. The direct opposite of it is a getter, which returns back an Object:
// in class Test
public Box getBox(){
return oBox;
}
另请检查以下内容: Java教程:面向对象的编程概念 [ ^ ].
*我们对类的讨论不多,它通常是一个对象.
Please also check out this: The Java Tutorials: Object-Oriented Programming Concepts[^] for more and detailed information.
* We do not talk much about classes, it''s usually an object.
这篇关于在Java中将类作为参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!