包装类作用主要是包装基本数据类型,包装为对象数据类型
例:实现大小写字母的相互转换
package *; class A{ private char ch;
public A(){} public A(char ch){this.ch=ch;}
public char getCh(){return this.ch;} public char daXie(){ if (ch>='A' && ch<='Z') { return (char)(ch+32);//ASCII是Unicode的子集 } return ch; } public char xiaoXie(){ if (ch>='a' && ch<='z') { return (char)(ch-32); } return ch; } } public class San { public static void main(String[] args) { char ch='r'; A a=new A(ch); char c=a.getCh(); System.out.println(c); } }
定义一个抽象类,实现圆形,矩形和三角形的面积计算。
package *; abstract class TuXing{ public abstract double getMianJi(); } class Yuan extends TuXing{ private double r; public Yuan(){}; public Yuan(double r){this.r=r;} public double getMianJi() { return Math.PI*r*r; } } class JuXing extends TuXing{ private double x; private double y; public JuXing(){} public JuXing(double x, double y){ this.x=x;this.y=y; } public double getMianJi() { return x*y; } } class Sanjiaoxing extends TuXing{ private double a; private double b; private double c; public Sanjiaoxing(){} public Sanjiaoxing(double a,double b,double c){ this.a=a;this.b=b;this.c=c; } public double getMianJi() { double p=(this.a+this.b+this.c)*0.5; double d=p*(p-this.a)*(p-this.b)*(p-this.c); double mianji=Math.sqrt(d); return mianji; } } public class Wu { public static void main(String[] args) { System.out.println(method(new Yuan(2))); System.out.println(method(new JuXing(2,3))); System.out.println(method(new Sanjiaoxing(3,4,5))); } public static double method(TuXing tuXing) { return tuXing.getMianJi(); } }