zoukankan      html  css  js  c++  java
  • System.out.print()与toString()

    在Java里面,每一个类都会隐式地继承object类,而在object类里面有toString方法,这个就是用来输出类地地址。
    System.out.println(this) 它会自动调用this对象的toString方法,所以若不重写toString方法地话,就会调用object类地toString方法,也就是输出当前对象的地址。
    示例:

    package test1;

    public class Student {
        private int price;
        private String category;
        
        public int getPrice() {
            return price;
        }
        public void setPrice(int price) {
            this.price = price;
        }
        public String getCategory() {
            return category;
        }
        public void setCategory(String category) {
            this.category = category;
        }
        
        
        public Student(int price, String category) {
            this.price = price;
            this.category = category;
        }
    //重写toString方法
        public String toString(){
            return "price:"+price+"category:"+category;
        }
    }

    输出Student
    package test1;

    public class StudentTest {

        public static void main(String[] args) {
            Student st=new Student(1,"category");
            System.out.print(st);
        }
    }

    结果 price:1category:category
    若不重写toString方法则输出 test1.Student@142bece



  • 相关阅读:
    vue.js 源代码学习笔记 ----- html-parse.js
    vue.js 源代码学习笔记 ----- text-parse.js
    vue.js 源代码学习笔记 ----- keep-alives
    一些图片剪切组件.
    好听的粤语歌..
    jQuery框架Ajax常用选项
    form自动提交
    .NET EF 框架-实现增删改查
    简单抓取小程序大全,并展示
    C#关于调用微信接口的代码
  • 原文地址:https://www.cnblogs.com/Lanyuxuan/p/5235949.html
Copyright © 2011-2022 走看看