• java----object类


     toString()使用:

    public class Demo {
        public static void main(String[] args){    	
        	Student s1 = new Student();
        	System.out.println(s1);  //自动执行s1.toString();
        }
    }
    
    class Student{
    	private int id;
    	private String name;
    	public Student(){};
    	public Student(int id,String name){
    		this.id = id;
    		this.name = name;
    	}
    	public String toString(){  //重写toString(),建议
    		return "id="+this.id+",name="+this.name;
    	}
    }
    

      

     equals使用:

    字符串

    public class Demo {
        public static void main(String[] args){    	
        	String a = new String("HH");
        	String b = new String("HH");
        	System.out.println(a==b);         //false
        	System.out.println(a.equals(b));  //true  //字符串对象重写了equals方法
        	
        	String c = "hh";
        	String d = "hh";
        	System.out.println(c==d);         //true
        	System.out.println(c.equals(d));  //true
    
         Integer a = 127; //Integer相当于引用和int基本数据类型不同
         Integer b = 127;	
         System.out.println(a==b); //true,由于享元模式,java解释器会缓存1个字节中的数,第二次创建127,就直接 从缓存返回数据;
         System.out.println(a.equals(b)); //true
         Integer c = 128;
         Integer d = 128;
         System.out.println(c==d); //false,由于128大于一个字节,不缓存,就会每次新new出一个对象.
         System.out.println(c.equals(d)); //true
    
        }
    }
    

      

    对象

    public class Demo {
        public static void main(String[] args){    	
        	Student s1 = new Student(1,"hh");
        	Student s2 = new Student();
        	System.out.println(s1==s2);         //false
        	System.out.println(s1.equals(s2));  //false
        }
    }
    

    如果需求是两个对象的传递的值是一样的,那么我们就认为两个对象是相等的,此时需要重写equals方法

    public class Demo {
        public static void main(String[] args){    	
        	Student s1 = new Student(1,"hh");
        	Student s2 = new Student(1,"hh");
        	System.out.println(s1.equals(s2));  //true  重写了equals方法
        }
    }
    
    class Student{
    	private int id;
    	private String name;
    	public Student(){};
    	public Student(int id,String name){
    		this.id = id;
    		this.name = name;
    	}
    	public String toString(){  //重写toString(),建议
    		return "id="+this.id+",name="+this.name;
    	}
    	public boolean equals(Object obj){  //使用object接受
    		if(this == obj){
    			return true;
    		}
    		else{
    			if(obj instanceof Student){
    				Student s = (Student)(obj);
    				if(s.id==this.id&&s.name.equals(this.name)){
    					return true;
    				}
    			}
    		}
    		return false;
    	}
    }
    

      

      

  • 相关阅读:
    PHP mysqli 扩展库(面向对象/数据库操作封装/事务控制/预编译)
    php 下载文件的函数
    PBOC电子钱包与电子现金及QPBOC
    基于PBOC电子钱包的消费过程详解
    PBOC规范下的java卡介绍
    基于PBOC电子钱包的圈存过程详解
    电子钱包和电子现金的区别
    DES,3DES,AES这三种对称密钥的区别与联系
    密钥体系
    关于卡片的主控密钥和应用主控密钥
  • 原文地址:https://www.cnblogs.com/yanxiaoge/p/10666713.html
Copyright © 2020-2023  润新知