This question already has answers here:
What does the 'static' keyword do in a class?
(22 answers)
Closed 4 years ago.
I've been running through a few tutorials for Java, they all say to make a new variable when calling classes. Why is this? I've tested some code and it works without doing this.
I've been using python for quite a while now so I'm used to using a dynamic language.
Please see some code I've been playing around with below:
import java.util.Scanner;
class MyClass {
static String myName(String name) {
return ("Your name is: "+name);
}
static String myAge(Integer age){
return ("Your age is: "+age);
}
static String myGender(String gender){
return ("You are: "+gender);
}
}
class Test{
public static void main(String [ ] args){
Scanner ui = new Scanner(System.in);
MyClass user = new MyClass();
//Output with new variable of class - user
String input = ui.next();
String newname = user.myName(input);
System.out.println(newname);
//Output calling class directly
Integer input1 = ui.nextInt();
String newage = MyClass.myAge(input1);
System.out.println(newage);
//Output with new variable of class - user
String input2 = ui.next();
String newgender = MyClass.myGender(input2);
System.out.println(newgender);
}
}
Thanks for your time.
If everything in the class is static (as in the code you posted), then there's no need to create instances of the class. However, if the class were to have instance fields and/or methods, then the story is different. For instance, consider a class like this:
class Person {
private String name;
private int age;
private String gender;
public Person(String name, int age, String gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
String myName() { return "Your name is: " + name; }
String myAge() { return "Your age is: " + age; }
String myGender() { return "You are: " + gender; }
}
Then you could create several Person instances with different internal state and use them interchangeably in your code:
public static void main(String[] args) {
Person jim = new Person("Jim", 40, "male");
Person sally = new Person("Sally", 12, "female");
report(jim);
report(sally);
}
private static report(Person person) {
System.out.println(person.myName());
System.out.println(person.myAge());
System.out.println(person.myGender());
}
If we create any member with static keyword it get memory at once to all objects, static keyword we used when we have common properties in class and we don't want to create separate memory to all instances objects ... it doesn't need to create instance variable to call it and this static block is shareable to to all objects.... for example if we have Animal class and we want to describe 5 different type of dog's ... than we don't define color, size like properties as static ... because they all have their own different size and color.... I hope you get it
Related
I'm trying to create two objects of each Man and Woman class with complete data using a constructor, with constructor that have all possible parameters.
I'm getting an error stating :
"invalid method declaration; return type required".
My code :
public class Solution {
public static void main(String[] args) {
Man man1 = new Man();
System.out.println(man.name + "" + man.age + "" + man.address);
Man man2 = new Man();
System.out.println(man.name + "" + man.age + "" + man.address);
Woman woman1 = new Woman();
System.out.println(woman.name + "" + woman.age + "" + woman.address);
Woman woman2 = new Woman();
System.out.println(woman.name + "" + woman.age + "" + woman.address);
//write your code here
}
private String name = "Mark";
private int age = 23;
private String address = 16527;
public Man(String name, int age, String address) {
this.name = name;
this.age = age;
this.address = address;
}
public Woman(String name, int age, String address) {
this.name = name;
this.age = age;
this.address = address;//write your code here
}
}
Can someone please help me :(
Your class is named Solution which means that your constructor can be named only Solution. Create separate classes named Man and Woman and then add your constructors there.
Also, since you are creating an object using default constructor, make sure to add them too in the above mentioned classes.
In order to call new Man() or new Woman(), you need to create an empty constructor for each class. Alternatively, you can have no constructor at all in the class and let java construct the default constructor.
Based on your code, you can only initialize them via the constructor that you have create which are new Man("Mark", 23, "16527") and new Woman("Mary", 23, "16527")
May be your code will be like this:
public class Solution {
public static void main(String[] args) {
Man man1 = new Man(); // first way to create object
Man man2 = new Man("dhiraj",28,"Indore"); // second way to create object
System.out.println(man2.name + "" + man2.age + "" + man2.address);
Woman woman1 = new Woman(); // first way to create object
Woman woman2 = new Woman("dhiraj",28,"Indore"); // second way to create object
System.out.println(woman2.name + "" + woman2.age + "" + woman2.address);
//write your code here
}
}
class Man
{
private String name, address;
private int age;
public Man()
{
}
public Man(String name, int age, String address) {
this.name = name;
this.age = age;
this.address = address;
}
}
class Woman
{
private String name, address;
private int age;
public Woman()
{
}
public Woman(String name, int age, String address) {
this.name = name;
this.age = age;
this.address = address;//write your code here
}
}
It seems you are new to Java. The code you've provided has a lot of mistakes.
(For ex:) Constructor should have the same name as the class
While defining an object using a constructor parameters should be passed as arguments(If not default constructor will be called) and etc. Please refer This link to get more idea about java classes and objects.
Your main problem, the cause of the error invalid method declaration; return type required is that you are putting the constructor for Man and Woman inside another (Solution) class. They should be defined in their own class. This error you're getting means that the compiler thinks there is a regular method declaration without a return type. It just thinks you made a method called Man(with some arguments) and a method called Woman (with some arguments).
Additionally, if you want that data to actually be part of the Man or Woman class, you should make sure it becomes part of those objects. You could make a constructor with those arguments or add it through setter methods later. The data won't magically appear in those objects just by constructing them with an empty constructor.
Create and implement a class Person. A Person has a firstName and friends. Store the names of the friends as a String, separated by spaces. Provide a constructor that constructs a Person with a given name (passed through arguments) and no friends. Provide the following methods:
public void befriend(Person p)
public void unfriend(Person p)
public String getFriendNames()
public int getFriendCount()
*Hint - you can use p.name to access the name of the Person passed to a method as an argument.
Include a Tester class to make sure your Person has some friends.
How do I store the names of the friends as a String, separated by spaces. (I have to be able to input the names from the main method). I also have no idea how to get rid of already inputted name using the method "unfriend"
public class Person
{
private String firstName;
private String friendNames;
private int friendCount;
public Person(String name)
{
firstName = name;
friendCount = 0;
}
public String getFriendNames()
{
return friendNames;
}
public double getFriendCount()
{
return friendCount;
}
public void befriend(String name)
{
friendNames = friendNames + " " + name;
friendCount++;
}
public void unfriend(String name)
{
String[] parseNames = friendNames.split(name);
friendNames = parseNames[0] + parseNames[1];
friendCount--;
}
}
Main Method:
public class PersonTester {
public static void main(String[] args) {
Person p = new Person("Alex");
p.befriend("John");
p.befriend("Alice");
p.befriend("Mike");
p.befriend("Annette");
p.unfriend("Alice");
System.out.println(p.getFriendCount());
System.out.println(p.getFriendNames());
}
}
Expected output:
2
John Mike
The problems you are having with the methods using the parameter(Person p) are because you have two different variables: friendName (which exists) and name (which does not). Changing the variable friendName to name will take care of some of the errors you are receiving.
(Also the method getFriendCount() returns friendsCount, but should return friendCount (you have an extra s in there) and your assignment calls for a method called befriend, not bestFriend.)
How to delete friends:
You can delete a friend by parsing the friend out of the friendNames string and then concatenating the two resulting strings back together:
public void unfriend(String name)
{
String[] parseNames = friendNames.split(name);
friendNames = parseNames[0] + parseNames[1];
friendCount--;
}
I would suggest changing befriend and unfriends parameters to accept a String instead of a Person object. Person already has access to its own object and in your main you are trying to pass them Strings anyways. Here is what befriend should look like:
public void befriend(String name) //Changed to "befriend"
{
friendNames = friendNames + " " + name;
friendCount++;
}
Also, you only need one constructor for Person, which should look like this:
public Person(String name)
{
firstName = name;
friendCount = 0;
}
When I run your program (using these changes) I get the following output:
2.0
John Mike
This question already has answers here:
Setter methods or constructors
(10 answers)
Why use getters and setters/accessors?
(37 answers)
Closed 6 years ago.
In the below code I've already declared that room = r; subject = s; and time = t; in the user defined constructor, so why is it necessary to do so again in set methods, my lecturer specifically asked that we add set methods for the room subject and time but it's redundant code as when I comment it out it still works. Do you only need to include set methods when there is no used defined constructor? What could be the advantage of having them set methods there?
class LectureTest{
public static void main (String [] args){
Lecture l1 = new Lecture(140, "Comp", 5);
l1.display();
Lecture l2 = new Lecture(280, "Sports", 3);
l2.display();
Lecture l3 = new Lecture(101, "Business", 5);
l3.display();
Lecture l4 = new Lecture(360, "Shooting", 4);
l4.display();
Lecture l5 = new Lecture();
l5.display();
}
}//end of LectureTest
class Lecture{
private int room;
private String subject;
private int time;
Lecture(int r, String s, int t){
room = r;
subject = s;
time = t;
}
Lecture(){}
public void setroomNumber(int r){
room = r;
}
public void setSubject(String s){
subject = s;
}
public void setTime(int t){
time = t;
}
public int getroomNumber(){
return room;
}
public String getSubject(){
return subject;
}
public int getTime(){
return time;
}
public void display(){
System.out.printf("\n" + "Room Number: " + getroomNumber() + "\n" + "Subject: " + getSubject() + "\n" + "Time " + getTime() + "\n");
}
}
The constructor "initializes" your values.
Let's say you have...
public class Person {
public String name;
public int age;
public Person (String name, int age) {
this.name = name;
this.age = age;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public String toString() {
String str;
str = "My name is "+name+" and I am "+age+" years old!";
return str;
}
}//End of Person
public class Main {
public static void main(String [] args) {
Person person = new Person("Bob", 15);
System.out.println(person.toString());
System.out.println("Switching my name...");
person.setName("Joe");
System.out.println(person.toString());
}
}//End of main
You see the difference? You should use the constructor if you want to create a new instance of the object. This way, you can set all the fields of the object at once and not need to call 490832490 setters (in this case, one for name and one for age...). You then can use the setter approach when you want to change the value of a field, PRIOR TO the object been created.
I DID ALL THIS ON THIS FORUM SO I MIGHT HAVE SYNTAX ERRORS SO CAREFUL...DIDN'T USE AN IDE IF YOU WANT TO TEST IT
The set methods make your object mutable. If you don't have the set methods and your variables are private then the Object will be immutable. You won't be able to change the values after it is constructed...If the values need to change you would have to create a new Object.
"Setters" allow you to modify private attributes of your object after instantiating. For example:
Lecture l1 = new Lecture(140, "Comp", 5);
//Since "room" is private you can't write l1.room = 4
//and have to use the setter method instead:
l1.setroomNumber(4);
l1.display();
They are also very useful if you want to do something if an attribute changes.
Let's assume you are using Observers, then you could call notifyObservers() or setChanged() in your setter method and never have to worry about these methods not getting called if your attribute changes.
I have these two files, personalinfo.java which defines the personalInfo class, and testpersonalinfo.java which tests the class. When I try to access my getter methods from testpersonalinfo.java I receive an error that these methods are undefined. Can anybody please tell me why?
personalinfo.java:
public class personalInfo {
private String name;
private String address;
private int age;
private long phoneNumber;
personalInfo(){
name = "Default Name";
address = "Default Address";
age = 100;
phoneNumber = 0000000000;
}
personalInfo(String nam, String add, int ag, int phone){
name = nam;
address = add;
age = ag;
phoneNumber = phone;
}
public String getName(){
return name;
}
public String getAddress(){
return address;
}
public int getAge(){
return age;
}
public long getPhoneNumber(){
return phoneNumber;
}
public void setName(String nam){
this.name = nam;
}
public void setAddress(String add){
this.address = add;
}
public void setAge(int ag){
this.age = ag;
}
public void setPhoneNumber(long phone){
this.phoneNumber = phone;
}
}
testpersonalinfo.java:
import java.util.Scanner;
public class personalInfoExample {
public static void main(String[] args){
personalInfo[] pers = new personalInfo[3];
Scanner input = new Scanner(System.in);
String inName;
String inAddress;
int inAge;
long inPhoneNumber;
for(int i=0; i<3; i++){
pers[i] = new personalInfo();
System.out.printf("Please input the name for person %s: ", i );
inName = input.nextLine();
pers[i].setName(inName);
System.out.println(pers[i].getName);
System.out.printf("Please input the address for person %s: ", i );
inAddress = input.nextLine();
pers[i].setAddress(inAddress);
System.out.println(pers[i].getAddress);
System.out.printf("Please input the age for person %d: ", i );
inAge = input.nextInt();
pers[i].setAge(inAge);
input.nextLine();
System.out.println(pers[i].getAge);
System.out.printf("Please input the phone number for person %d, without dashes included (ex. 1112223333): ", i );
inPhoneNumber = input.nextLong();
pers[i].setPhoneNumber(inPhoneNumber);
System.out.println(pers[i].getPhoneNumber);
input.nextLine();
}
input.close();
}
}
The getters are functions, not fields; so to call them you need to use () (like in: pers[i].getAdress().
Also, class names should be capitalized, but it's not really important (just makes it easier to read.
As someone suggested in a comment, you should use an IDE, in case you are not doing it. The IDE will point you to the obvious little mistakes (both errors and convention mistakes) like the ones above, and save you a long time. If you don't know where to get started for that, search Eclipse or Netbeans. (Eclipse is my personal favourite).
EDIT: I just saw Eran commented the answer to your error, so if he posts it as an answer accept his first.
in all your sysout statements you are trying to access getter without () this.
please try this
System.out.println(pers[i].getName()); //change all your getters
instead of
System.out.println(pers[i].getName);
because getName() is a method not a Variable so always you need to use open-close braces () just after the method name
(either you defining or calling) .
please change all these methods (methods which raise an compile-time Error).
System.out.println(pers[i].getName);
System.out.println(pers[i].getAddress); //all these lines are causing of Compile time error.
System.out.println(pers[i].getAge);
System.out.println(pers[i].getPhoneNumber);
In case if you don't want to use getter method to access instance variable(Other than private variables) out side of the class defination, you can call instance variable-names directly on an instance object like
pers[i].name
For more on variables access control please refer java-doc
I have two classes. In the first one, I used the Scanner to retrieve the user's name and then store it in a String called name. Then say, I start a new class, and want to print that came out, how do I go about it. So I just wrote up this code as an example, so you can get an idea of what I'm trying to ask. I'll post both classes.
import java.util.Scanner;
public class One {
public static void main(String[] args) {
String name;
String start;
Scanner input = new Scanner(System.in);
System.out.println("Hello, what is your name?");
name = input.nextLine();
System.out.println("Hello "+name+", welcome! To ocntinue, please hit any key.");
start = input.nextLine();
if(start != null){
Two object = new Two();
}
}
}
Second class.
public class Two {
public Two() {
System.out.println("Ok "+One.name+", lets start!");
}
}
So, you will probably be doing something like this: -
class One
{
private String name = "bob";
public String getName()
{
return name;
}
public static void main(String [] args)
{
One one = new One();
Two two = new Two(one);
// You could also just pass an r-value to Two, as in, Two(new One()) if you
// never require 'one' again
}
}
class Two
{
public Two(One one)
{
System.out.println("Ok " + one.getName() + ", lets start!");
}
}
What is going on?
Creating two classes in your main entry point method.
Passing the instance of One to the constructor of Two
Two then calls getName()
You could, as others have suggested, pass a string as the constructor; alternatively, you could do both if required as Java supports overloading methods see
Recommendations
Take a look at http://docs.oracle.com/javase/tutorial/java/javaOO/methods.html for overriding methods so that you may see how to pass both a string and an object reference by value. What you are doing right now is passing the object reference of one by value. It may not be needed or you may want to provide restrictions using an interface, see http://docs.oracle.com/javase/tutorial/java/concepts/interface.html
Use the constructor to pass the values
public class Two {
private String value;
public Two(String a){
this.value=a;
System.out.println("Ok "+value+", lets start!");
}
//getter and setters
}
Then while creating the instance use that constructor
Two object = new Two(name);
pass your value to the Two class constructor.
if(start != null){
Two object = new Two(start );
}
and
public Two(String s){
System.out.println("Ok "+s+", lets start!");
}
To make your code compile, move the String name variable into a static field:
public class One {
public static String name;
public static void main(String[] args){
// Note: The "name" variable is no longer defined here
String start; // etc
// rest of code the same
}
}
I'm not going to tell you this is good code design, but it does what you asked.
You will also do like this
public class One {
private String name;
public void setName(String name){
this.name = name;
}
public String getName(){
retrun this.name;
}
public static void main(String[] args){
String name;
String start;
Scanner input = new Scanner(System.in);
System.out.println("Hello, what is your name?");
name = input.nextLine();
System.out.println("Hello "+name+", welcome! To ocntinue, please hit any key.");
start = input.nextLine();
if(start != null){
Two two = new Two();
two.printName(this);
}
}
class Two{
public void printName(One one){
System.out.println("" + one.getName() );
}
}