It says that public user number is an invalid method. It states that the part of the code is invalid and requires a return type.
public UserNumber(){
super();
randy = new java.util.Random();
} //=======================
What do I do to fix it?
In Java method has to have return type (int, Integer, Random) or void if it is not intended to return anything. Add void after public.
public void UserNumber() {
...
}
There is a chance you wanted to create a class constructor, but then its name has to be the same as the class name. For example:
public class UserNumber {
private final Random randy;
public UserNumber() {
super();
randy = new Random();
}
}
(in that case calling super() can be omitted - it is performed anyway)
Please provide full code of this class.
Unless you class is called UserNumber, you need to add a return type to the method declaration:
public void UserNumber(){
randy = new java.util.Random();
}
void as return type, since that method won't return anything.
If you, instead, wanted to make it a constructor, the name of the constructor must be the same of the class.
class UserNumber extends ...{
public UserNumber(){
super();
randy = new java.util.Random();
}
...
}
Constructor name should be identical as your class name!
public class UserNumber {
public UserNumber() {
super();
randy = new java.util.Random();
}
}
To invoke this special method use: new UserNumber() - this is all :)
More:
Java: How can a constructor return a value?
Add void after public. Every method needs a return type and this will set it to return nothing.
You are missing the return type. It must be Whether void, int or any object type.
The call to super() makes me think that this is supposed to be a constructor. Your class must be called UserNumber
In this case you do not need a return type, since constructors always return a new instance of the class.
If it's not a constructor, get rid of the call to super(), as you may only call that in a constructor. Also make sure that the class you're extending has a parameterless constructor.
I think1 that the real problem is that you are confused over the difference between a method and a constructor, and you are trying to use a constructor as if it was a method.
Your UserNumber so-called method is actually declared (properly!) as a constructor1. The way to use is as a constructor is as follows:
UserNumber myNum = new UserNumber();
I suspect you are trying to call it like:
... = UserNumber();
... and that is going to fail, saying that UserNumber is an invalid method. A Java constructor is invoked using new.
There are 3 clues that say to me that the OP's code is intended to be a constructor:
The super() syntax is only valid in a constructor.
A method declaration requires a return type AND a method name. This has only one identifier before the parameter list.
You've used an identifier that should be a class name (according to the Java identifier rules).
1 - I can't be sure, because you didn't show us the line with the syntax error on it. Or if you did, then the real problem is somewhere else ... in code that you haven't shown us.
Related
I have been assigned to make a class using both default and parameter constructor but the thing is, is that even possible? I don't get how it can even work..both are supposed to assign values to variables
Borrowed from this answer from #bohemian
public class Person
...
public Person() {
this("unknown", 0); // you can call another constructor
}
public Person(String nm, int ag) {
name = nm;
age = ag;
}
...
}
In this example if the no-args constructor is called then unknown and 0 will be passed to the other constructor
When you define another constructor in your class, you do not get the "usual" default constructor (public and without arguments) anymore.
However, you can add it back in:
class MyClass{
MyClass(String param){} // custom constructor
MyClass(){} // bring back the non-arg one
}
Of course, when creating an object instance using new you have to choose which one to call (you cannot have both):
MyClass instanceA = new MyClass("a string");
MyClass instanceB = new MyClass();
The constructors can call each-other (using this(parameters)) or shared methods if there is common functionality in them that you want to keep in one place.
Actually you can't do that in Java, by definition.JLS ยง8.8.9, http://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.8.9 says, "If a class contains no constructor declarations, then a default constructor is implicitly declared." So as soon as you add any constructor declaration, even a no-arg constructor, you don't get a default constructor.
I am a beginner in Java. I have two packages in my current project. Each of the packages have two classes called the "packageClassOne" and "packageClassTwo".
The packageClassTwo has a constructor and other public methods.
I want to call the PackageClassTwo from an if statment located in the PackageClassOne. My code looks something like this
packageClassOne:
public class packageClassOne {
public void selectComponent(boolen) {
if(/* check condition*) {
packageClassTwo value = new packageClassTwo();
}
}
}
packageClassTwo:
public class packageClassTwo {
public packageClassTwo(String name){ //Constructor
int length = name.length();
}
public String CreateWord(){
/*functionality ofthis method*/
}
public String CreateSentence(){
/*functionality ofthis method*/
}
}
The problem is that everytime I call the packageClassTwo from my packageClassOne it tries to call the constructor instead of calling the class itself. I want to call the entire packageClassTwo instead of just the constructor.
Can somebody help me please? Thank you in advance for your help
Since Java is an object oriented language, you have to have a mindset of dealing with instances that are realizations of the classes you defined. These are the objects.
So if you want to call a method from packageClassTwo class, you first create an object of packageClassTwo. You seem to be trying to do just this. Once you have the object, you can call its methods. For example
//Instantiate an object by calling the constructor
packageClassTwo object = new packageClassTwo(string);
//Now call its methods
String val = object.CreateWord()
There is no such thing as "calling a class". You call methods of objects of a class.
Occasionally, there might be a well founded need to call methods of a class without initializing objects. Look into static methods and classes for further reading.
If you want to call all methods of packageClassTwo you have to do it explicitly
packageClassTwo pct = new packageClassTwo("");
pct.CreateWord();
pct.CreateSentence();
If you allways want the 2 methods to be called when you create a new packageClassTwo object, than you can just add the calls to the constructor
public packageClassTwo(String name) {
int length = name.length();
pct.CreateWord();
pct.CreateSentence();
}
Edit:
Note that in the second case, if you end up only calling the 2 methods from inside the constructor, it is better to make them private.
As a sidenote, it is a general convention in java to have class names start with a upper case letter : PackageClassTwo not packageClassTwo, and method names to start with lower case createWord not CreateWord. This wll make your code more readable.
If you want to call all the methods from the packageClassTwo, call them from the packageClassTwo constructor
public packageClassTwo(String name)
{
int length = name.length();
CreateWorld();
CreateSentence();
}
I don't think your code will run without compiling errors.because you did not declare the constructor packageClassTwo().
I cannot understand how this constructor works:
public class Multiply {
//and here i've got this atypical for me constuctor
Multiply mult(Multiply a){
Multiply tmp;
//code here
return tmp;
}
}
There is no constructor here, in your case a default constructor will take place, and an instance of the class without any special operation will perform on the 'new' word
A constructor has the same name as the class and no return type. What you have right there is a method called mult with the return type Multiply. You might be confused because the visbility modfier is missing. This is totally valid as the default visibility protected is used in this case.
It's the same as:
protected Multiply mult(Multiply a)
A constructor would look like this:
public Multiply(Multiply a)
If no constructor is declared, the default constructor is implicitly added to your class. So the class has a constructor that looks like this:
public Multiply() {
super();
}
I am amateur in Java please help me.
I have a class: Account
public class Account {
protected String fullName;
protected String accontNumber;
protected String password;
protected int balance;
public Account(String name, String acc_num, String pass, int b){
fullName = name;
accontNumber = acc_num;
password = pass;
balance = b;
}
}
and I going to create a new class Account2 that inherit from Account
public class Account2 extends Account{
public Account2(String l){
String[] temp = l.split(",");
super.fullName = temp[0];
super.accontNumber = temp[1];
super.password = temp[2];
super.balance = Integer.parseInt(temp[3]);
}
}
But I receive an error message that say: Actual and formal argument list are differ in length
how can I solve this problem?
When the base class has a non-default constructor (one or more parameter), the derived class must call the base class constructor in its constructor with super(paramters). And also notice for constructor, you must have the first line with the super statement, so you must declare a construct with the same parameter, or correctly pass in the parameter within one line, though this is not recommended:
public Account2(String l) {
super(l.split(",")[0],l.split(",")[1],l.split(",")[2],Integer.parseInt(l.split(",")[3]));
}
do like this
public class Account2 extends Account{
public Account2(String l){
super(l.split(",")[0],l.split(",")[1],l.split(",")[2],Integer.parseInt(l.split(",")[3]))
}
}
You haven't placed the super constructor call. So by default it will try to pick super() i.e. no-argument constructor which is not present in Account class
Your current subclass constructor sets the values of the superclass parameters after superclass construction. If you would like to keep that approach, add a no-arg constructor to the superclass that sets default values.
It would be better to use setters rather than accessing the fields directly.
IMHO in this case you sholudn't use a constructor. Create a static method that takes your String input, validates it, splits it into some logical parts and then uses "normal" constructor to create an object:
class Account2 extends Account {
Account2(String name, String acc_num, String pass, int b) {
super(name, acc_num, pass, b);
}
public static Account2 createFromString(String input) {
String[] temp = l.split(",");
if (temp.length != 4) {
throw new RuntimeException("...");
}
return new Account2(temp[0], temp[1], temp[2], Integer.parseInt(temp[3]));
}
}
Your code will be a lot cleaner in my personal opinion:
Account2 acc1 = new Account2("abc", "def", "ghi", 2);
Account2 acc2 = Account2.createFromString("abc,def,ghi,2");
The probelm:
Actual and formal argument list are differ in length
To understand this, a basic understanding of constructors and their behavior under inheritance will help you.
When we define a class without constructors, the compiler inserts a zero argument constructor by itself.
If we write our own constructor with some argument then this default constructor is not inserted by compiler and if required, it has to be added explicitly.
When an instance of a subclass is created , there is an implicit call (very first thing to get executed during constructor invocation) to the superclass constructor by default.
So, if there is no default constructor in superclass (which will be the case when we define our own custom constructor with argument), the compiler will complain.
To get around this, you need to call the constructor with argument as very first line in the subclass constructor or define a default constructor explicitly.
Heres some sample code,
class Base
{
private int val;
Base() {
val = lookup();
}
public int lookup() {
//Perform some lookup
// int num = someLookup();
return 5;
}
public int value() {
return val;
}
}
class Derived extends Base
{
private int num = 10;
public int lookup() {
return num;
}
}
class Test
{
public static void main(String args[]) {
Derived d = new Derived();
System.out.println("d.value() returns " + d.value());
}
}
output: d.value() returns 0 // I expected 10 as lookup() is overridden, but not 0! can someone clarify this?
The initialization of Derived's instance variables has not happened at the time its lookup method executes. How do I make sure the instance variables of Derived are initialized when its method is called?
Well for a start, that code doesn't compile due to the lack of someLookup method.
Anyway, asides from that I believe your issue is that your expections are invalid because of the way constructors are run hierarchically.
A superclass' constructor is always run before the subclass', and this includes initializers for the subclass' variables (which are really run as part of the constructor). So, when you create your instance of Derived, the following happens:
The Base constructor is invoked first.
lookup() is called, which uses the implementation in Derived.
num is returned, which is the default value at this point because Derived's constructor and initializers have not been run.
val is set to 0.
The Derived initializers and constructor are run - calling lookup from this point on will return 10.
In general, it's a bad idea to call a non-final method from a constructor for exactly this reason, and many static analysis tools will warn you against it. It's similar to letting object references leak during construction, you can end up with an instance that invalidates class-level invariants (in your case, Derived's num is "always" 10 yet it can be seen to be 0 at some points).
Edit: Note that for this particular case, without any additional code, you could resolve the issue by making num a constant:
class Derived extends Base
{
private static final int num = 10;
...
This would actually do what you want, because the static initializer is run when the class is loaded (which has to happen before the constructors are called). This does however assume that it's fine for:
a) all instances of the class to share the same num variable;
b) num never needs to change (if this is true then (a) is true automatically).
In the exact code you've given this is clearly the case, but I expect you may be omitting extra functionality for brevity.
I include this here for comparison and interest, not because it's a workaround to this "issue" in a general sense (because it's not).
The reason you are getting 0 returned is that the constructors Base is being called (and calling lookup in Derived) before 10 is assigned to num in Derived.
To put generally, the base constructor is called before the derived instance fields are initialised.
There are a lot of great answers already on why you can't access subclass fields while constructing the base class, but I think you asked for a how: a working solution for something like this:
public abstract class Animal {
public Animal() {
System.println(whoAmI());
}
public abstract String whoAmI();
}
public Lion() extends Animal {
private String iAmA = "Lion";
public Lion(){super();}
public String whoAmI() {return iAmA;}
}
The practical way is to introduce an init() method on the base class an call it from the subclass's constructor, like:
public abstract class Animal {
private boolean isInitialized = false;
public Animal() {}
void init() {
isInitialized = true;
System.out.println(whoAmI());
}
public abstract String whoAmI();
public void someBaseClassMethod() {
if (!isInitialized)
throw new RuntimeException("Baseclass has not been initialized");
// ...
}
}
public Lion() extends Animal {
private String iAmA = "Lion";
public Lion() {
super();
init();
}
public String whoAmI() {return iAmA;}
}
Only problem is, you can't force subclasses to call the init() method on the base class and the base class might not be properly initialized. But with a flag and some exceptions we can remind the programmer at runtime that he should have called init()...
It is generally a bad idea to call methods in a constructor that can be overriden in a subclass. In your example the following happens:
Derived constructor is called
Base constructor is called as its first action
Base constructor calls lookup
Derived constructor continues and initialies num to 10
Since the subclass constructor is not finished when the base constructor calls lookup, the object is not yet completely initialized and lookup returns the default value of the num field.
Let's take it slowly:
class Test
{
public static void main(String args[]) {
// 1
Derived d = new Derived();
// 2
System.out.println("d.value() returns " + d.value());
}
}
Step 1, you call the (default) constructor on Derived, before setting num = 10, it chains up to Base's constructor, which calls Derived's lookup method, but num has not been set, so val remains uninitialized.
Step 2, you call d.value(), which belongs to Base, and val is unset due to 1, and therefore you get 0 instead of 10.
You have overriden method lookup() in the Derived class, so when the Base constructor is called it calls the method from Derived which body is return num. At the time of Base initialization the num instance variable of the Derived is not yet initialized and is 0. That's why val is assigned to 0 in Base.
If I understood your intentions correctly, you should change the value method in Base to be:
public int value() {
return lookup();
}
The below piece of code is returing 0 (you would expect 10 by looking at the program) when the constructor makes a call to this. The simple reason is that num is not initialized yet and the parent class calls this method.
public int lookup() {
return num;
}