java - Constructing an object from a string -
is possible construct object given string, tostring() method, , class itself.
for example have class book.
class book { // ... string gettitle() { return title; } string getpubyear() { return pubyear; } void settitle(string _title) { title = _title; } void setpubyear(string _pubyear) { pubyear = _pubyear; } public string tostring(){ return title+" "+pubyear; } }
if have string:
"exampletitle 2017"
how can create instance of class book, has attribute:
title=exampletitle pubyear=2017
we can following:
book book = new book(); string examplestring = "exampletitle 2017"; string[] parts = examplestring.split(); book.settitle(parts[0]); book.setpubyear(parts[1]);
but long winded. there more automatic way this?
you can add new constructor:
public book(string s) { string[] parts = s.split(" "); if (parts.length() == 1) { this.title = s; } else { this.title=parts[0]; this.pubyear(integer.parseint(parts[1])); } }
you should add numberformatexception handling on own recommend post it.
the above constructor take string
, split space , perform have done. can use like:
book book = new book("example_title 2001");
but it's not best approach. should rather use standard patterns , first extract values want set book
, pass them constructor.
the way of doing want make constructor:
public class book { public book(string s, int y) { this.title = s; this.year = y; } }
please change year
field int
or long
. year shouldn't string
long you're not using roman numbers
.
Comments
Post a Comment