public class Sample1 {
public String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public static void main(String[] args) {
Sample1 s1= new Sample1();
s1.setName("Abc");
}
}
public class Sample2 {
public static void main(String[] args) {
Sample1 n2= new Sample1();
System.out.println(n2.getName());
}
}
I have two classes Sample1 and Sample2 two. I am allocating string value using setter method and returning in another class by using getter method, but an output is null. Why null is an output and how to get string value from one call to another class?
I think you misunderstood the main method, maybe I am wrong, however only one main method is executed.
If you run Sample2.main - on Sample1 you are not setting a name so it is null (Sample1.main is never executed).
If you run Sample1.main - Sample1 is created and assigned a name.
So either assign the name in the Sample2.main:
public static void main(String[] args) {
Sample1 n2= new Sample1();
n2.setName("xxx");
System.out.println(n2.getName());
}
or do it via constuctor.
public class Sample1 {
private final String name;
public String getName() {
return name;
}
public Sample1(String name) {
this.name = name;
}
}
Consider the code :
Sample1 n2= new Sample1();
System.out.println(n2.getName());
Here the Name is not set , So you need to set the name before getting the name.
Sample1 n2= new Sample1();
n2.setName("name goes here");
System.out.println(n2.getName());
Also, you can try parameterized constructor in the Sample1 class and access like in sample2 class:
Sample1 n2= new Sample1("your name goes here");
System.out.println(n2.getName());
The constructor will be :
public Sample2(String name){
this.name = n;
}
3 thing you can add method in Sample1 class and access it in Sample2 class.
I don't want to set String value in Sample2 class, need to assign string value in Sample1 only, after that i need that string value in Sample2 class
public class Sample1 {
private String _name;
public String getName() {
return _name;
}
private setName(String name) {
_name = name;
}
public SetNameHelper(){
setName("somestring");//You will be setting the name in Sample 1
}
}
public class Sample2 {
public static void main(String[] args) {
Sample1 n2= new Sample1();
n2.SetNameHelper();
System.out.println(n2.getName());//You will be getting Name in Sample 2 class
}
}
class Sample2 {
Sample1 sample1;
Sample2(Sample1 sample){
this.sample1 = sample;
}
private String getSample1Name() {
return this.sample1.getName();
}
public static void main(String[] args) {
Sample1 sample1 = new Sample1();
sample1.setName("Abc");
Sample2 n2= new Sample2(sample1);
System.out.println(n2.getSample1Name());
}
}
I think I understand you confusion: you mistake a main function for a constructor!
I noticed that you created a main function in each class, whose only role is to create an instance and set the internal fields of the class. It's probably a Constructor you were looking for.
Here's the deal:
A main method is the entry point of a program. It just stays, to run me: begin executing this code. You probably (99.9% of the case) need only one main method per project.
A Constructor is a method which creates an instance of, each class, i.e. an object you can manipulate elsewhere in your code. Read up on Object-Oriented Programming
So here is your example, fixed (I believe), in a way that can bring sample1 value into an sample2, as you say:
public class Sample1 {
public String name;
public String Sample1(String initialName){
this.name = initialName;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class Sample2{
public String name;
public String Sample2(String initialName){
this.name = initialName;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class ProgramEntryPoint{
public static void main(String[] args) {
Sample1 s1 = new Sample1("a name");
System.out.println("Initial sample1 name: " + s1.getName());
s1.setName("a New Name!");
System.out.println("New sample1 name: " + s1.getName());
Sample2 s2 = new Sample2(s1.getName());
System.out.println("Initial sample2 name: " + s2.getName());
}
}
Which, once you run ProgramEntryPoint.main, will print:
Initial sample1 name: a name
New sample1 name: a New Name!
Initial sample2 name: a New Name!
This is all simple Java stuff, you should read up a few basic tutorials (the ones on oracle website are a good start)
Related
Consider the following code for a read only interface pattern in Java:
package package2;
public interface AccountsReadOnly {
public String getValue();
}
package package1;
import package2.AccountsReadOnly;
class Accounts implements AccountsReadOnly {
private String name;
public Accounts() {
name = "unknown";
}
public String getValue() {
return name;
}
public void setValue(String name) {
this.name = name;
}
}
package package1;
public class Manager {
Accounts allAccess;
public Manager() {}
}
package package2;
public class Employee {
public AccountsReadOnly accountReadOnly;
public Employee() {}
}
public class Demo {
public static void main(String[] args) {
Manager m = new Manager();
Employee e = new Employee();
Accounts a = new Accounts();
m.allAccess = a;
m.allAccess.setValue("Andrew");
System.out.println(m.allAccess.getValue());
e.accountReadOnly = a;
System.out.println(e.accountReadOnly.getValue());
}
}
I can't understand this line as this is the first time for me to see this format:
m.allAccess.setValue("Andrew");
Is it possible to use instead of this line since they have the same reference?
m.setValue("Andrew");
Is m.allAccess a reference of the object?
Is it possible to use instead of this line since they have the same reference?
no, m.setValue("Andrew"); does not work, because the Manager-class has no function setValue
Is m.allAccess a reference of the object?
yes, allAccess references the Account-object which is set in this line: m.allAccess = a;
The getValue and setValue methods should really be named getNameand setName, because that what they do. setValueshould return a value, e.g. the account's balance.
Also nameis not read-only if you have a setter for it.
say we have 2 classes:
public class A {
private String name = "A";
public String toString()
{
return (name + "some random text");
}
}
public class B extends A{
private String name = "B";
public String toString()
{
return (super.toString());
}
}
When I tried to print the B.toString() in my driver class, it will still print the name from class A instead of the name from class B. How can I change it so it will use the variable name from class B instead?
You can do it through the use of constructors -
public class HelloWorld {
public static void main(String[] args) {
A a = new A("A String");
B b = new B("B String");
System.out.println(a.toString()); // A String some random text
System.out.println(b.toString()); // B String some random text
}
}
class A {
protected String name;
A(String name) {
this.name = name;
}
public String toString() {
return name + " some random text";
}
}
class B extends A {
B(String name) {
super(name);
}
#Override
public String toString() {
return (super.toString());
}
}
Because B inherits from A, the name field is setup correctly when you pass a string to the constructor for B.
I am having a bit of trouble getting started on this Java assignment, and was hoping to get some guidance from you guys. My issue is pretty simple and straightforward... How do I take the tester method's input and start using "Dave" as the new name? How do I make Dave the instance variable and how do I start using that in the setName() and greetCrewMember() methods? After that's done, how would I assign Aruna? The main thing tripping me up is the instance variable and calling it in the methods. Thanks for any help given!
public class Hal9000
{
private String name;
public static void main(String[] args)
{
Hal9000 hal = new Hal9000("Dave");
System.out.println(hal.greetCrewMember());
System.out.println("Expected: Welcome, Dave");
System.out.println(hal.doCommand("engage drive"));
System.out.println("Expected: I am sorry, Dave. I can't engage drive");
hal.setName("Aruna");
System.out.println(hal.doCommand("power down"));
System.out.println("Expected: I am sorry, Aruna. I can't power down");
}
public String getName()
{
}
public void setName(String newName)
{
String name = newName;
return name;
}
public String greetCrewMember()
{
String message = "Welcome," + name ;
return message;
}
public String doCommand(String whatToDo)
{
}
}
The only thing you have to do is to define a parameterised constructor-
Hal9000(String name)
{
this.name=name;
}
This will cause your statement-
Hal9000 hal = new Hal9000("Dave");
to execute correctly and set the name to Dave. After this you can set the name to anything else by your setname method.
You would also want to define something in your getname method.
You should use the field name within the constructor and use this to instantiate it within the setter and constructor.
Hal9000(String name) {
this.name = name;
}
further instantiate as
Hal9000 instanceForDave = new Hal9000("Dave"); // would set the 'name' for this instance as 'Dave'
Hal9000 instanceForAruna = new Hal9000("Aruna");
The setter implementation should ideally also make use of this name only, something similar to the constructor in your case as:
public void setName(String newName) {
this.name = newName;
}
and then when you need to fetch the name attribute of the class, the getter would be helpful as
public String getName() {
return this.name;
}
public class Hal9000
{
private String name;
public Hal9000(String[] stringArray) {
name = stringArray[0];
}
public static void main(String[] args)
{
String[] stringArray = { "Dave"};
Hal9000 hal = new Hal9000(stringArray);
System.out.println(hal.greetCrewMember());
System.out.println("Expected: Welcome, Dave");
System.out.println(hal.doCommand("engage drive"));
System.out.println("Expected: I am sorry, Dave. I can't engage drive");
hal.setName("Aruna");
System.out.println(hal.doCommand("power down"));
System.out.println("Expected: I am sorry, Aruna. I can't power down");
}
public String getName()
{
return this.name;
}
public void setName(String newName)
{
this.name = name;
}
public String greetCrewMember()
{
String message = "Welcome," + getName() ;
return message;
}
public String doCommand(String whatToDo) {
return whatToDo;
}
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
The code is having some problem with class 2 line 12. Kindly help .
The code is in the image.
import java.util.Scanner;
public class first{
public static void main(String[] args){
Scanner b = new Scanner(System.in);
pro nc = new pro();
System.out.println("Enter the name of your first true crush");
String temp = b.nextLine();
nc.setname(temp);
nc.etc();
}
}
public class pro{
private String gname;
public String getName() {
return gname;
}
public void setName(String name) {
this.gname = name;
}
public void etc(){
System.out.printf("The name of your true crush was %s",getName());
}
}
In class 2 you have not specified the location of the function in System.out.printf(). You should use the this keyword and re-write the function as
public class pro {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void etc(){
System.out.printf("The carp is %s",this.getName());
}
}
there is no problem with this
I AM USING NETBEANS IDE.
/*
///
public class pro {
private String gname;
public String getname() {
return gname;
}
public void setname(String name) {
gname = name;
}
public void etc(){
System.out.printf("Tht name is %s",getname());
}
}
/////////
import java.util.Scanner;
public class first {
public static void main(String[] args) {
Scanner b= new Scanner(System.in);
pro nc = new pro();
System.out.println("enter the name");
String temp = b.nextLine();
nc.setname(temp);
nc.etc();
}
}
/////////
*/
Recheck this.
I have not changed your code, just typed it.
And yes I agree with Arc676 that people should post the code.
There is no problem on netbeans.
You can try to use System.out.format instead of System.out.printf.
import java.util.Scanner;
public class first{
public static void main(String[] args){
Scanner b = new Scanner(System.in);
pro nc = new pro();
System.out.println("Enter the name of your first true crush");
String temp = b.nextLine();
nc.setname(temp);
nc.etc();
}
}
public static class pro{
private String gname;
public String getName() {
return gname;
}
public void setName(String name) {
this.gname = name;
}
public void etc(){
System.out.format("The name of your true crush was %s", getName());
}
}
What is wrong with my code? Compiler says non static variable cannot be referenced from a static context
package nestedclass;
public class Nestedclass {
class Student {
String name;
int age;
long roll;
public Student(String name, int age, long roll) {
this.name = name;
this.age = age;
this.roll = roll;
}
public void show() {
System.out.println("name : "+name+" age : "+age+" roll : "+roll);
}
}
public static void main(String[] args) {
//Nestedclass=new Nestedclass();
Student ob=new Student("ishtiaque",10,107060);
ob.show();
// TODO code application logic here
}
}
The nested Student class isn't static, that's why the compiler complains. There are a couple of ways to get out of this situation: make Student static, or instantiate Nestedclass and provide a nonstatic method in Nestedclass that does the actual work on an instance of Student, and that you call from main:
private void run() {
Student ob = new Student("ishtiaque", 10, 107060);
ob.show();
}
public static void main(String[] args) {
new Nestedclass().run();
}
or, if you like oneliners you could also do
public static void main(String[] args) {
new Nestedclass().new Student("ishtiaque", 10, 107060).show();
}
Personally I prefer the second method (with the helper method) as it's easier to refactor afterwards.
Your inner class is not declared as static; therefore, you cannot access it from the static method main. Change your inner class declaration to static class Student
You need to initiate the static class then Use the new of that class in order to initiate the their inner none classes. Or you can declare your Student inner class as static class.
first solution
Student ob = new Nestedclass().new Student("ishtiaque", 10, 107060);
second solution
static class Strung {...}
Hope that helps.
this will work
public class Student
{
String name;
int age;
long roll;
public Student(String name, int age, long roll) {
this.name = name;
this.age = age;
this.roll = roll;
}
public void show()
{
System.out.println("name : "+name+" age : "+age+" roll : "+roll);
}
public static void main(String[] args) {
Student ob=new Student("ishtiaque",10,107060);
ob.show();
}
}