面向对象0925

静态导入

例子

导入系统中的一些类

static修饰

类名.方法名()

import static(静态导入) java.util.Math.* //注意静态修饰

使用Math类时,不用再Math.sqry(x),直接sqrt(x)就可以。

foreach()循环,是for循环的简化变形版本

c#中为foreach()

double [] dos=new double[]{1,2,3,4,5};

Java中为for(int xx : dos)//注意冒号

public static void main(String args[]){
    double[] dos=new double p[]{1.0,2.3,3.4,5.6};
    for(int xx:dos){
        System.out.print(xx);//注意不是dos[i],foreach简化输出的形式
    }                
}
    

  

可变参数

可变参数输出的为数组,因为参数是多个,所以是数组

public static void main(String args[]){

  add(1,2,3);

}

public static int add(int...xyz){

int sum=0;

  for(int i=0;i<xyz.length;i++){

  sum+=i;

}

}//注意点

 instanceof关键字

instanceof 是用来在运行时指出对象是否是特定类的一个实例。instanceof通过返回一个布尔值来指出,这个对象是否是这个特定类或者是它的子类的一个实例。

用来判断对象属于那个类,可以是类的属性,也可以是多态的方法。

package *;

public class App {
	public static void main(String[] args) {
//		Person person=new Person();
//		Employee employee=new Employee();
//		
//		boolean b1=person instanceof Person; //基本语法
//		System.out.println(b1);
//		boolean b2=employee instanceof Person; //true
//		System.out.println(b2);
//		
//		boolean b3=person instanceof Employee; //false
//		System.out.println(b3);
//		boolean b4=employee instanceof Employee; //true
//		System.out.println(b4);
		
		//多态
		
		//Dog、Cat
		method(new Dog());
		method(new Cat());
	}
	public static void method(Animal x){
		if(x instanceof Dog){
			((Dog)x).fun1();
		}
		if(x instanceof Cat){
			((Cat)x).fun2();
		}

	}
}

包装类

包装类的作用主要是讲基本的数据类型封装成对象数据类型。

package Second;

class A{
	//包装类 基本数据类型包装后,通过对象调用普通方法
	private char ch;
	public A(){};
	public A(char ch){this.ch=ch;};
	public char method() {//小写转大写
		return (char)(ch-32);
	}
	public char method2() {//大写转小写
		return (char)(ch+32);
	}
}
public class Second {
	public static void main(String[] args) {
	char c1='c';
	A a=new A('c');
	char ch1=a.method();
	char ch2=a.method2();
	System.out.println(ch1);
	System.out.println(ch2);
	}
}

  

package com.oracle.zibo.chapter03.section04;

class Ixx{
	private int i;
	public Ixx(){}
	public Ixx(int i){
		this.i=i;
	}
}

public class App {
	public static void main(String[] args) {
		short s=2; //Short
		int i=3; //Integer
		long l=4; //Long
		float f=3.14F; //Float
		double d=4.14; //Double
		boolean b=false; //Boolean
		byte by=126; //Byte
		char ch='a'; //Character
		
		Integer inte1=new Integer("123");
		Integer inte2=new Integer(23);
		System.out.println(inte1.intValue()+inte2.intValue());

		Integer x=23; //自动装箱
		Integer y=2;
		//Emp emp1
		//emp1+emp2
		int z=x+y; //自动拆箱
		System.out.println(z);
	
		int xx=Integer.parseInt("234");
		System.out.println(xx);
		
		System.out.println(Double.parseDouble("3.14s"));
	}
}

  

原文地址:https://www.cnblogs.com/dldrjyy13102/p/7591573.html