Calling one variable of a class in another class? - java

Hi I am new to the java programming. I have a instance variable in a class which I should call to another class.It should not be static as per the requirements.The code given below## `
public class Card {
private String no;
private String text;
public Vector totalCards = new Vector();
public String getNo() {
totalCards.addElement(no);
return no;
}
public void setNo(String no) {
this.no = no;
}
public String getText() {
totalCards.addElement(text);
return text;
}
public void setText(String text) {
this.text = text;
}
}
I need to pass this "totalCards" vector in another class without making it as a static.How can I pass this value.Can anybody help me. Any suggestions appreciated.

Since the variable "totalCards" is public, it can be directly accessed via an instance of Card.

It's a bit unclear exactly what your issue is, but you first need to have an instance of Card. The totalCards Vector will then live in that Card object.
Card myCards = new Card();
Now the object that has access to myCards can access the Vector with:
myCards.totalCards
However, it's considered a better practice by many to make totalCards private and make a getter for it:
myCards.getTotalCards();

You simply write in your class:
public class AnotherClass
{
public Class obj1 = new Class();
public String getNo()
{
Vector v1 = obj1.totalCards;
return v1; //or what do you want
}

You can simply pass totalCards reference to other class because is public. Tell us more about client class. Thanks.

public class Card {
private String no;
private String text;
/* initializing totalCards here is bad, why are you doing this here? If each
card has a list of totalCards, consider doing this in the constructor of a
Card */
private Vector<Card> totalCards = new Vector();
public String getNo() {
//getters should not have side effects like addElement...
totalCards.addElement(no);
return no;
}
public Vector<Card> getCards() {
return totalCards;
}
public void setNo(String no) {
this.no = no;
}
public String getText() {
//getters should not have side effects like addElement...
totalCards.addElement(text);
return text;
}
public void setText(String text) {
this.text = text;
}
}

The other class needs to have an instance of Card. For example by creating a new instance:
public class TheOtherClass {
private Card myCard = new Card();
public void doSomething() {
myCard.totalCards.doAnotherThing();
}
}
By the way: It's considered as bad style to access properties of other classes directly - try to use setters and getters:
public class Card {
private Vector<Card> totalCards = new Vector();
public void getTotalCards() {
return totalCards;
}
}

Related

How to access a private object within a private object in Java?

I am trying to access an object within an object here. Below are the three classes. I simplified this that it makes the same error as in the full program.
This is the main class.
import java.util.Scanner;
public class TestMain
{
public static void main (String[] args)
{
createStudent();
}
public static Student createStudent()
{
Student another = new Student();
another.depart(101,"CS");
return another;
}
}
The second one,
public class Student
{
private int sid;
private String sname;
private Department department;
public int getSid()
{
return sid;
}
public String getSname()
{
return sname;
}
public void depart(int departid, String departname)
{
department.setDid(departid);
department.setDname(departname);
}
public void setSid(int stusid)
{
this.sid = stusid;
}
public void setSname(String stusname)
{
this.sname = stusname;
}
}
The third one,
public class Department
{
private int did;
private String dname;
public int getDid()
{
return did;
}
public String getDname()
{
return dname;
}
public void setDid(int deptdid)
{
this.did = deptdid;
}
public void setDname(String deptdname)
{
this.dname = deptdname;
}
}
No matter what I do, this program returns a run time error,
Exception in thread "main" java.lang.NullPointerException
at Student.depart(Student.java:17)
at TestMain.createStudent(TestMain.java:13)
at TestMain.main(TestMain.java:7)
What is NullPointerException and how to avoid this? Please help me.
The exception is occurring because you did't create the object in the depart method. You can use this:
public void depart(int departid, String departname)
{
department = new Department();
department.setDid(departid);
department.setDname(departname);
}
The problem is that when you create a Student object, you need to initialize each member object i.e. the department object is null, so when you do department.setDid(101), it returns an exception.
To fix this, create a custom constructor for the Student class as so:
Student()
{
department = new Department();
sid = 0;
sname = "";
}
Edit: As Sebastian has rightly pointed out in the comment below, it's actually pretty unnecessary to initialize primitive types in constructors. However, please note that you must do this for String types, as their default value is null, not "", which could cause problems later on.
in your department class in depart method you don't create instance of department and department field is null use this instead:
department = new Department();
public void depart(int departid, String departname){
department = new Department();
department.setDid(departid);
department.setDname(departname);
}

Access a method of a class defined within a method

It seems like PdCar class have been upcast to Car type, and I can't find a way to use methods that are not in Car interface. I'm just curious, is there a way to access readLabel method? Or it's just not possible?
Thanks.
interface Car{
}
public class Parcel5 {
public Car car(String s){
class PdCar implements Car {
private String label;
private PdCar(String whereTo){
label = whereTo;
}
public String readLabel(){ return label; }
}
return new PdCar(s);
}
public static void main(String [] args){
Parcel5 p = new Parcel5();
Car d = p.car("toyota");
}
}
It seems like PdCar class have been upcast to Car type
no.
If you want to access methhod readLabel() you have to declare it in the interface Car.
I can't find a way to use methods that are not in Car interface. I'm just curious, is there a way to access readLabel method? Or it's just not possible? Thanks.
interface Car{
String readLabel()
}
public class Parcel5 {
public Car car(String s){
class PdCar implements Car {
private String label;
private PdCar(String whereTo){
label = whereTo;
}
public String readLabel(){ return label; }
}
return new PdCar(s);
}
public static void main(String [] args){
Parcel5 p = new Parcel5();
Car d = p.car("toyota");
System.out.println(d.readLabel());
}
}

Can outclass specify inner class with InnerClassNameOuter directly rather than ClassName.InnerClassName

In Inner classes of Thinking In Java,
If you want to make an object of the inner class anywhere except from
within a non-static method of the outer class, you must specify the
type of that object as OuterClassName.InnerClassName, as seen in
main().
But I find use InnerClassName directly still works in main.
public class Parcel2 {
class Contents {
private int i = 42;
public int value() { return i; }
}
class Destination {
private String label;
Destination(String whereTo){
label = whereTo;
}
String readLabel(){ return label; }
}
public Destination to(String s){
return new Destination(s);
}
public static void main(String[] args){
Parcel2 q = new Parcel2();
/* Destionation d = q.to("Borneo"); still works.*/
Parcel2.Destination d = q.to("Borneo");
}
}

Declaring a nested class in Java

I'm a bit confused with subclasses.
Here's my code:
public class MedHistory {
private String grafts;
private String allergies;
private String diseases;
private String surgeries;
private String medicalTreatment;
//Constructors (#2)
public MedHistory(String allergies, String diseases, String grafts,
String treatments, String surgeries) {
this.allergies=allergies;
this.diseases=diseases;
this.grafts=grafts;
this.medicalTreatment=treatments;
this.surgeries=surgeries;
}
public MedHistory() {
this.allergies="";
this.diseases="";
this.grafts="";
this.medicalTreatment="";
this.surgeries="";
}
//Getters
public String getGrafts() {
return grafts;
}
public String getAllergies() {
return allergies;
}
public String getDiseases() {
return diseases;
}
public String getSurgeries() {
return surgeries;
}
public String getMedicalTreatment() {
return medicalTreatment;
}
//Setters
public void setGrafts(String grafts) {
this.grafts = grafts;
}
public void setAllergies(String allergies) {
this.allergies = allergies;
}
public void setDiseases(String diseases) {
this.diseases = diseases;
}
public void setSurgeries(String surgeries) {
this.surgeries = surgeries;
}
public void setMedicalTreatment(String medicalTreatment) {
this.medicalTreatment = medicalTreatment;
}
public class FemMedHistory extends MedHistory {
private List<Birth> births = new ArrayList<Birth>();
//Constructors (#2)
public FemMedHistory(String allergies, String diseases, String grafts,String treatments, String surgeries, List<Birth> birthlist) {
super(allergies,allergies,grafts,treatments,surgeries);
this.births=birthlist;
}
public FemMedHistory() {
super();
this.births=null;
}
//Getter
public List<Birth> getBirths() {
return this.births;
}
//Setter
public void setBirths(List<Birth> list) {
this.births=list;
}
}
}
When I try to create an new FemMedHistory object like this:
List<Birth> list = new ArrayList<Birth>();
list.add(new Birth(new GregorianCalendar(2011,4,10),"kaisariki",4));
FemMedHistory female = new FemMedHistory("allergia2","astheneia2","emvolia2","farmekeutiki agwgi2", "xeirourgeia2", list);
I get the error:
No enclosing instance of type MedHistory is accessible. Must qualify
the allocation with an enclosing instance of type MedHistory (e.g.
x.new A() where x is an instance of MedHistory).
So, which is the right way to use a subclass?
When you declare a nested class it only available through the Outer class.
To access it outside, you will need to either make the FemMedHistory class static.
public static class FemMedHistory extends MedHistory {...}
access it through the MedHistory class
MedHistory.FemMedHistory myMedHistory = ...
or declare it in it's own Java file.
You have declared your subclass as an inner class, which means that you can't create an instance of it without first creating an instance of the containing class.
The most common way to solve this is to declare it as a separate class, which would get rid of your error.
Long story short: cut all the FemMedHistory code and paste it into FemMedHistory.java. The way it is now you have involved Java concepts which you have not yet mastered. Also, that class really does belong in a separate file.

Json Jackson deserialization without inner classes

I have a question concerning Json deserialization using Jackson.
I would like to deserialize a Json file using a class like this one:
(taken from http://wiki.fasterxml.com/JacksonInFiveMinutes)
public class User
{
public enum Gender { MALE, FEMALE };
public static class Name {
private String _first, _last;
public String getFirst() { return _first; }
public String getLast() { return _last; }
public void setFirst(String s) { _first = s; }
public void setLast(String s) { _last = s; }
}
private Gender _gender;
private Name _name;
private boolean _isVerified;
private byte[] _userImage;
public Name getName() { return _name; }
public boolean isVerified() { return _isVerified; }
public Gender getGender() { return _gender; }
public byte[] getUserImage() { return _userImage; }
public void setName(Name n) { _name = n; }
public void setVerified(boolean b) { _isVerified = b; }
public void setGender(Gender g) { _gender = g; }
public void setUserImage(byte[] b) { _userImage = b; }
}
A Json file can be deserialized using the so called "Full Data Binding" in this way:
ObjectMapper mapper = new ObjectMapper();
User user = mapper.readValue(new File("user.json"), User.class);
My problem is the usage of the inner class "Name". I would like to do the same thing without using inner classes. The "User" class would became like that:
import Name;
import Gender;
public class User
{
private Gender _gender;
private Name _name;
private boolean _isVerified;
private byte[] _userImage;
public Name getName() { return _name; }
public boolean isVerified() { return _isVerified; }
public Gender getGender() { return _gender; }
public byte[] getUserImage() { return _userImage; }
public void setName(Name n) { _name = n; }
public void setVerified(boolean b) { _isVerified = b; }
public void setGender(Gender g) { _gender = g; }
public void setUserImage(byte[] b) { _userImage = b; }
}
This means to find a way to specify to the mapper all the required classes in order to perform the deserialization.
Is this possible? I looked at the documentation but I cannot find any solution.
My need comes from the fact that I use the Javassist library to create such classes, and it does not support inner or anonymous classes.
Thank you in advance
There should be no difference between the static inner class Name, and the top-level class of the same name. The Jackson runtime should not be able to meaningfully distinguish between the two situations.
Have you tried moving the Name class out of User, changing it into a top-level class? It should still work as before.
edit: I just tried this, and it works fine when Name is a top-level class. The example had it as an inner class for the sake of brevity, I suspect.
mr. Skaffman's answer is right on. The only additional thing to mention is that unlike JAXB, Jackson does not generally require you to specify classes you operate on, except for the root class (and not always even that, if you use Polymorphic Handling).

Categories

Resources