2013年9月8日星期日

In new a java object, how to control whether the programmer must implement a method

Now if I have a java class User
There is a
public void setName () {

}
Methods

as well as two of the User class constructor
public User () {

}

public User (String name) {

}

I now want other people in the new user when a User object , if
user = new User (); using a no-argument constructor, create an instance , you must override setName method
And if
user = new User (" Joe Smith " ) ; using a constructor argument to establish entities , they do not cover the setName method .
how can I do to control others such as I mean to go new a User object
------ Solution ------------------- -------------------------
add a flag, which represents a call constructor in the constructor to flag assignment . In accordance with the method set different flag to determine whether an exception is thrown .

java is not a dynamic language , want to completely let outside to see the internal methods, estimates more difficult.
------ Solution ---------------------------------------- ----
lz not the provider constructor with no arguments , ah, there is only one argument constructor , he can only use a parameter in the form of your first written unless it is an abstract class.
------ Solution ---------------------------------------- ----


abstract class User {
public abstract void setName();
}

class NamedUser extends User {

public NamedUser(String userName) {
}

@Override
public void setName() {
}
}






class User {
 public User(String userName) {
}
}



The first direct new user object if it must implement the set method, if new nameduser you must provide a user name

The second must provide a user name , there is no no-argument constructor
------ For reference only --------------------- ------------------
My goal is to make other programmers in the use of new a User object is passed when the control code compilation
If
user = new User ();
Such direct new a java object can not compile the .
If you want to compile , you must follow the following two written to compile
1. either override setName method
user = new User () {
public void setName () {

}
};

2. Either use constructors with parameters
user = new User (" Joe Smith " ) ;

instead like you said during the execution of the program throwing an exception , my purpose is to control the programmer to new object


------ For reference only ---------------------------------- -----
you're right, I thought for a moment to the question I raised , or that it must implement an abstract method of problem, the problem is still not resolved, but thank you.

没有评论:

发表评论