zoukankan      html  css  js  c++  java
  • Object类的方法,toString的重写.

    Object类是所有类的根类。

    Object类是所有类的父类,位于java.lang包中 数组也是Object类的子类

    Object类的常用方法 toString(); equals(); hashCode();

    任何类的对象,都可以调用Object类中的方法,包括数组对象。系统默认存在继承Object类。

    例如

    public class Example{ 
          public void f(Object obj){
          }    
        }
        public class Test{
          public static void main(){
             Example exam=new Example();
             int[] array=new int[4];
             ……//任何数组
             exam.f(array);
        }
        }

    toString方法; toString方法可以将任何一个对象转换成 字符串返回,返回值的生成算法为:getClass().getName() + '@' + Integer.toHexString(hashCode())。

    例如:toString ()的方法重写。 

    class Goods {
        String name ;
        int coding;
        int price;
        int num;
        Goods(String name,int coding,int price,int num){
            this.name = name ;
            this.coding = coding; 
            this.price = price;
            this.num = num;
    //        coding = textField.getText();
    //        name = textField_1.getText();
    //        num = textField_2.getText();
    //        price = textField_3.getText(); 
        }
    
        public String toString (){
            return "  编号: "+coding+"  姓名: "+name+"  数量: "+num+"  价格: "+price;
            
        }
    public static void main (String [] args){
            Goods  good = new Goods("张三",022,12510,0021);
            System.out.println(good);
    }    

    equals方法; Object类中的equals方法,用来比较两个引用的虚地址。当且仅当两个引用在物理上是同一个对象时,返回值为true,否则将返回false。

    一般方法中equals比较的是两个对象的值。因为一般方法都被toString重写。

    hashCode方法 获取对象的哈希码值,为16进制 equals方法与hashCode方法关系 如果两个对象使用equals比较返回true,那么它们的hashCode值一定要相同 如果两个对象equals比较返回false,那么它们的hashCode值不一定不同   覆盖equals,往往需要覆盖hashCode,可以使用Eclipse自动生成,保证equals返回true,则hashCode相同;equals返回false,则hashCode不同 在Set集合部分有实际应用

  • 相关阅读:
    第二章整理
    汇编实验二
    汇编实验一
    第一章整理
    第一部分 | 第1章 —— Hello Cocos2d-x
    返回 *this 的成员函数以及 const重载
    C++中的const
    680. Valid Palindrome II
    字典树
    单调队列
  • 原文地址:https://www.cnblogs.com/fy02223y/p/7152332.html
Copyright © 2011-2022 走看看