方法的参数传递机制:只能是值传递
package Collection;
public class ZhiCd {
//此处如果不加静态static
//Exception in thread "main" java.lang.Error: Unresolved compilation problem:
// Cannot make a static reference to the non-static method swap(int, int) from the type ZhiCd
public static void swap(int a,int b)
{
int temp;
temp = a;
a=b;
b=temp;
System.out.println("swap:"+"a:"+a+" "+"b:"+b);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int a=9;
int b=6;
swap(a, b);
System.out.println("a:"+a+" "+"b:"+b);
}
}
package Collection;
class DataWrap
{
int a;
int b;
}
public class ReferenceTransferTest {
/**
* @param dw
*/
public static void swap(DataWrap dw)
{
int temp;
temp=dw.a;
dw.a=dw.b;
dw.b=temp;
System.out.println("DataWrap方法"+dw.a+" "+dw.b);
}
public static void main(String[] args) {
DataWrap dw=new DataWrap();
// DataWrap dw=null;
dw.a=6;
dw.b=9;
swap(dw);
System.out.println("DataWrap方法后"+dw.a+" "+dw.b);
}
}
递归方法:
例子:
f(0)=1,f(1)=4,f(n+2)=2*f(n+1)+f(n)
package Collection;
public class Recursive {
public static int fn(int n)
{
if(n==0)
{
return 1;
}
else if(n==1)
{
return 4;
}
else {
return 2*fn(n-1)+fn(n-2);
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(fn(10));
//10497
}
}
setter和getter方法:
package Collection;
public class Person {
//使用private修饰成员变量
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
//执行合理性校验,要求用户名必须在2-6位之间
if(name.length()>6||name.length() <2)
{
System.out.println("您设置的人名不符合要求");
return;
}
else
{
this.name=name;
}
}
public int getAge() {
return age;
}
public void setAge(int age) {
//执行合理性校验,要求用户年龄必须在0-100
if(age>100||age<0)
{
System.out.println("您输入的人名不正确");
return;
}
else{
this.age = age;
}
}
}
super:
package Collection;
import java.util.Scanner;
class BaseClass
{
public int a=5;
}
public class SubClass extends BaseClass {
public int a=7;
public void accessOwner()
{
System.out.println(a);
}
public void bccessOwner()
{
//super限定只能从父类取得实例变量和方法
System.out.println(super.a);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
SubClass subClass=new SubClass();
subClass.accessOwner();
subClass.bccessOwner();
}
}