简体   繁体   中英

Illegal combination of modifiers: public and private

I am having an issue with the following code...

/**
 * This class holds all of the information pertaining to 
 * a person's name.
 */
public class Name {

    private String first, middle, last, maiden, initials, prefix, suffix;
    private char middleInitial, firstInitial, lastInitial;
    private

    /**
     * Constructor for a Name given first, middle, and last names.
    */
    public Name(String first, String middle, String last) {

        this.first = first;
        this.middle = middle;
        this.last = last;
        this.middleInitial = middle.charAt(0);
        this.firstInitial = first.charAt(0);
        this.lastInitial = last.charAt(0);
        this.initials = String.valueOf(firstInitial + middleInitial 
            + lastInitial);
        this.maiden = null;
        this.prefix = null;
        this.suffix = null;

    }

There is more but my error is coming in my primary constructor. It is giving me the error that I have entered in the title. As you can see, both my class and constructor are both public. This shouldn't cause any issues but seems to be doing so.

You have an "orphan" private modifier before the constructor's comment:

private // Here!

/**
 * Constructor for a Name given first, middle, and last names.
 */
public Name(String first, String middle, String last) {

Just remove it, and you should be fine.

There is a stray private on the third line inside the class. Since statements last until a curly brace or semicolon is encountered, the compiler thinks that this is a part of the same statement as your constructor declaration - it sees private public Name(String first, String middle, String last) .

After declaring all your variables, you have written the keyword private .

private String first, middle, last, maiden, initials, prefix, suffix;
private char middleInitial, firstInitial, lastInitial;
private  // Here.  

Java is a freely-typed language. A line ends with a ; (semi colon) and not a newline. So

private  

public Name(String first, String middle, String last) {
    // ...
}  

is considered to be one single line as:

private public Name(String first, String middle, String last) {  
  // ...
}  

As you can see, your constructor has two modifiers, public and private . Which is illegal in Java.

Solution

  1. Remove the keyword public if you want to keep the constructor private and want other classes to instantiate it. 希望其他类实例化它,请删除关键字public

OR

  1. Remove the keyword private if you want to allow other classes to instantiate it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM