Logic cannot understand - java

I am trying to understand java class and object relation but facing one problem.
Here I have one simple java bean class:
public class Student {
int id;
String name;
String marks;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMarks() {
return marks;
}
public void setMarks(String marks) {
this.marks = marks;
}
}
And one Editor class:
public class EditStudent {
public static void editStd(Student st){
st.setId(10);
st.setName("editAbleName");
st.setMarks("133");
// return st;
}
I am writing this logic for student object in my program class:
public class TestProgram {
public static void main(String args[]){
System.out.println("main");
Student std = new Student();
std.setId(1);
std.setName("zeeshan");
std.setMarks("44");
EditStudent.editStd(std);
System.out.println("id " +std.getId());
System.out.println("name " +std.getName());
System.out.println("marks " +std.getMarks());
}
}
Output:
main
id 10
name editAbleName
marks 133
I supposed that I will get output values of my object that I set on my test program class but getting output values of those which I set on my EditStudent class.
Why this happen even I think there is no relation between my std object and editStudent Class ?
Please explain me logic occurs behind this logic and process!

std is not an Object. It is a reference to an Object. So, when you pass it to the method editStd, you pass the reference to the Object.
Therefore, std and st refer to the same object(as they store the same reference) Thus, any changes to the object pointed by st, is also reflected in std, as they are the same.

EditStudent.editStd(std);-- Even if you are passing modified object of std in editStd method, editStd again modifies std object with values in the method. This is because std and s object refers to same object on heap.

your EditStudent class will get inherit through your argument of student class (st) you have made. You don't need to define the values of Base class (student) in EditStudent class. your testprogram class is correct then it will override the values of EditStudent Class and you will get the output of your derived class(testprogram). So remove the values from EditStudent Class.

You are passing a reference to the Object.
In Edit student
EditStudent.editStd(std); // In java It is a reference
// IN C++ You used to write '&' in your method(function)
but in Java it is not like that. Java doesn't have pointers --> either
Since you are new I will tell you how to write the class properly
public class Student {
// Make them PRIVATE
private int id;
private String name;
private String marks;
// create constructor
Student(){} // empty
Student(int id, String name, Strings marks){
this.id = id;
this.marks = marks;
this.name = name;} // overloaded, If you want
// use Getter and setter for only Private field.. NO need for Public
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMarks() {
return marks;
}
public void setMarks(String marks) {
this.marks = marks;
}
}
Benefit of overloaded constructor
public class TestProgram {
public static void main(String args[]){
System.out.println("main");
/* Student std = new Student();
std.setId(1);
std.setName("zeeshan");
std.setMarks("44"); */
// benefit of overloaded constructor
Student s = new Student(1,"zeeshan", 44);
// you only need one line
// EditStudent.editStd(std); // Here you are passing the reference to your object to another class.. Which changes the original
// If you want to edit student Make a method in Student class
// I am following your logic
// create an empty student and pass it.
Student s2 = EditStudent.editStd( new Student() );
// return the student from editstd goto method it is below
System.out.println("id " +std.getId());
System.out.println("name " +std.getName());
System.out.println("marks " +std.getMarks());
}
}
public class EditStudent {
public static Student editStd(Student st){
// return type student
st.setId(10);
st.setName("editAbleName");
st.setMarks("133");
return st;
}

Related

How can I set data in a Constructor if all parameters are private?

I have to write a code for example
public class Student {
private int id;
private String name;
public Student (int id, String name) {
this.id=id;
this.name=name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Now, in MAIN CLASS I have to get all values from user
How am I supposed to set value in constructor??
like this?
String name = input.nextLine();
int id = input.nextInt();
Student student = new Student (id, name);
"THE ISSUE WITH THIS METHOD IS THAT, WE CAN'T KEEP THE ATTRIBUTES PRIVATE THEN, BECAUSE THEY ARE NOW LOCAL VARIABLES"
OR
I create a constructor with no parameters and use that object to get values and set in fully parametrized constructor.
Student st = new Student();
student.setName(input.nextLine());
student.setID(input.nextInt());
Student student = new Student (st.getId, st.getName);
I don't know if I was able to explain what I want, but if you get that, do let me know
I would use this approach
Student st = new Student();
st.setName(input.nextLine());
st.setID(input.nextInt());
But both are fine . You don't really need to create the second student object in the second example. Just use the one you created upfront
To access the name and ID later you can do
String name = st.getName();
int id = st.getID();
(Edit - this assumes you do make a no arg constructor)

i want to print a method in an object of on object array but cant. why?

i am trying to understand why cant i print this method. it doesn't show me that there is any problem with my code so i can't figure out what am i missing here.
package practice;
class Persons{
String name;
int id;
public void speak(String name,int id) {
System.out.println("hello i am " + name + " and my id is " + id);
this.name = name;
this.id = id;
}
}
public class demo1 {
public static void main(String[] args) {
Persons person[] = new Persons[5];
person[0].speak("guy", 1);
}
}
You are creating an array of 5 null elements. This code will throw NullPointerException.
Persons person[] = new Persons[5];
person[0] = new Person();
person[0].speak("guy", 1);
You may consider creating a constructor of type:
public Persons(String name,int id)
Or expose a public set of getters and setters.

I'm having a hard time understanding and implementing a constructor and I'm looking for some guidance

I'm learning about constructors, but the videos that I've watched don't seem to help and everything I find on google seems to describe it in an advanced way.
I want to write a simple program which takes two inputs, a name (String) and an id (integer) and then just outputs it as "id" - "name". So for example:
01 - hello
This is the program that I'm trying to fix:
import java.util.Scanner;
public class ConstructorTest {
public static void main(String[] args) {
ConstructorTest();
toString(null);
}
//Constructor
public ConstructorTest(){
Scanner name = new Scanner(System.in);
Scanner id = new Scanner(System.in);
}
// Method
public String toString(String name, int id) {
System.out.print(id + " - " + name);
return null;
}
}
The errors that I get, are saying that my methods and constructors are undefined.
A constructor creates ("constructs") a new object. You can then call methods against that object.
Here's a simple object:
public class MyObject {
private int id;
private String name;
public MyObject(int id, String name) {
this.id = id;
this.name = name;
}
// Other methods here, for example:
public void print() {
System.out.println(id + " " + name);
}
}
You would call this constructor like this:
MyObject thing = new MyObject(1, "test");
And then you could call its method like this:
thing.print();
So for your example, what you'd do in your main method is first prompt the user for id and name, then create an object using a constructor, and then call a method on the constructor.
public class ConstructorTest {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// get the id and name from the scanner (I would suggest using prompts)
String name = in.nextLine();
int id = in.nextInt();
// create an object:
ConstructorTest myObject = new ConstructorTest(id, name);
// call the method:
String myString = myObject.toString();
// print the result:
System.out.println(myString);
}
// private variables, effectively the "properties" stored by the object:
private int id;
private String name;
// constructor:
public ConstructorTest(int id, String name) {
this.id = id;
this.name = name;
}
// method
#Override // because this is a method in java.lang.Object and we're overriding it
public String toString() {
return id + " - " + name;
}
}
Try this:
import java.util.Scanner;
public class ConstructorTest {
private int id;
private String name;
public static void main(String[] args) {
String name = args[0];
int id = Integer.valueOf(args[1]);
ConstructorTest ct = new ConstructorTest(name, id);
System.out.println(ct);
}
public ConstructorTest(String n, int i) {
this.id = i;
this.name = n;
}
// Method
public String toString() {
return String.format("%d - %s", id, name);
}
}
Never, ever put I/O in a constructor.

Using Object class Reference variable, accessing different class members.

I am trying to access class members of different class i.e.,getDetails() from student as well as customer class using Object class Reference variable. But it looks like its not working. Please look into this easy code and help me out how to access the getDetails() using Object class ob[0] and ob[1]
class Customer
{
int custId;
String name;
Customer(String name, int custId)
{
this.custId = custId;
this.name = name;
}
public void getDetails()
{
System.out.println(this.custId+" : "+this.name);
}
}
class Student
{
int roll;
String name;
Student(String name, int roll)
{
this.name = name;
this.roll = roll;
}
public void getDetails()
{
System.out.println(this.roll+" : "+this.name);
}
public static void main(String []args)
{
Object[] ob = new Object[2];
ob[0] = new Student("Vishal", 041);
ob[1] = new Customer("Xyz" , 061);
ob[0].getDetails();
ob[1].getDetails();
}
}
Try creating a common interface that declares the method getDetails. Something like this:
public interface Person {
public void getDetails();
}
Let Student and Customer implement the interface. Then declare the array like this:
Person ent[] ob = new Person[2];
....

new to java constructor help needed

I have an past exam question that says:
"Create a class Element that records the name of the element as a String and has a public method, toString that returns the String name. Define a constructor for the class (that should receive a String to initialise the name)."
I gave it a go and don't where to go from here...
main class is:
public class builder {
public static void main(String[] args) {
element builderObject = new element(elementName);
}
}
and constructor is:
import java.util.*;
class element {
public int getInt(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter the first number");
String elementName = scan.nextLine();
System.out.println("%s");
}
public String toString() {
return elementName;
}
}
Don't get frustrated. Please read java tutorials first and understand the concepts. your exam question is very clear on what you need to do. Atleast for this question, you need to know what is constructor, the purpose of having toString() in a class.
May be the below can help you.
public class Element {
private String elementName;
public Element(String elementName) {
this.elementName = elementName;
}
#Override
public String toString() {
return elementName;
}
}
I can't think of a way to explain this without actually giving the answer, so....
public class Element { /// Create class Element
private final String name; // Record the 'name'
public Element(String name) { // constructor receives and sets the name
this.name = name;
}
public String toString() { // public method toString() returns the name
return name;
}
}
You are missing the constructor itself. The point of constructors is to initialize the object, usually by saving the given parameters to data members.
E.g.:
class Element {
/** A data member to save the Element's name */
private String elementName;
/** A constructor from an Element's name*/
public Element(String elementName) {
this.elementName = elementName;
}
#Override
public String toString() {
return elementName;
}
}
class Element {
private String name = "";
/**
/* Constructor
/**/
public void Element(final String name){
this.name = name;
}
#Override
public String toString(){
return name;
}
}
You don't have a constructor in there. A constructor typically looks something like this:
public class MyClass {
private String name;
private int age;
//This here is the constructor:
public MyClass(String name, int age) {
this.name = name;
this.age = age;
}
//here's a toString method just for demonstration
#Override
public String toString() {
return "Hello, my name is " + name + " and I am " + age + " years old!";
}
}
You should be able to use that as a guideline for making your own constructor.
class Element
{
private String name = "UNSET";
public String getName() { return name; }
public Element(String name) {
this.name = name;
}
public String toString() {
return getName();
}
}
You are missing a constructor you might be looking for something like this
public class Element{
private String name;
public Element(String name){ //Constructor is a method, having same name as class
this.name = name;
}
public String toString(){
return name;
}
}
A note
I take you are starting with java, In java class names usually start with capital letter, thus element should be Element. Its important that one picks up good habits early..

Categories

Resources