java - sending variables through nested classes - java

I have a class that has a variable of type Name.
public class Holder {
private Name name;
private int snumber;
The Name class has two strings called first and last that are assigned values by setter methods. I would like to send over the strings from the Name class to name in the Holder class, but I'm having trouble doing so. I think I've taken a step in the right direction by doing this
public class Holder {
private Name name;
private int snumber;
public void setName(){
name = new Name();
name.getFirst();
name.getLast();
}
but I can't say that I really know what the correct approach is. I also tried name.setFirst(getFirst) but that doesn't work. Any ideas would be appreciated.

The same way you would if the class wasn't nested.
Your setName() method should take a parameter (maybe 2, first and last) and then invoke the name.setFirstName(), name.setLastName() methods.
Right now, your setName() method isn't doing anything.
E.G:
public class Holder
{
private Name name;
private int snumber;
public Holder()
{
this.name = new Name();
}
public void setName(String firstName, String lastName)
{
this.name.setFirst(firstName);
this.name.setLAst(lastName);
}
}

Here is a good article explaining the relationship between Java inner and outer classes:
https://www.tutorialspoint.com/java/java_innerclasses.htm
class Outer_Demo {
// private variable of the outer class
private int num = 175;
// inner class
public class Inner_Demo {
public int getNum() {
System.out.println("This is the getnum method of the inner class");
return num;
}
}
}
public class My_class2 {
public static void main(String args[]) {
// Instantiating the outer class
Outer_Demo outer = new Outer_Demo();
// Instantiating the inner class
Outer_Demo.Inner_Demo inner = outer.new Inner_Demo();
System.out.println(inner.getNum());
}
}
Note that the example creates instances of both "Outer_Demo" AND "Inner_Demo (outer.new Inner_Demo();).

Ok, so I figured something out that works.
public class Holder {
private int snumber;
private Name name;
public void setName(Name n){
name=n;
}
public Name getName(){
return name;
}

Related

how should i add an object to a private static ArrayList?

i have Bank class, with a private static ArrayList that stores all the banks. how can i add every new bank created to it?
i'm not allowed to create any new methods or fields, or change any of the method or constructor parameters.
this is my Bank class:
public class Bank {
private static ArrayList<Bank> allBanks=new ArrayList<Bank>();
private String name;
public Bank(String name) {
this.name = name;
}
public String getName() {
return name;
}
and this is my Main class:
public class Main {
public static void main(String[] args) {
new Bank("randomBankName");
}
}
Do it in constructor:
public Bank(String name) {
this.name = name;
allBanks.add(this);
}
WARNING never do it in real project.
You didn't say, that you may not change the visibility of fields, so that would be one way to do this: make the ArrayList public
If you may not do this either, there is a last way, which i'd never do: Reflection.
In most cases, thats really the last way, not recommended!

Initialize a class having another class object as member variable

This is my first class:
package trickycorejava;
public class InnerClass {
int id;
oneClass oneClass;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public trickycorejava.oneClass getOneClass() {
return oneClass;
}
public void setOneClass(trickycorejava.oneClass oneClass) {
this.oneClass = oneClass;
}
public InnerClass(int id, trickycorejava.oneClass oneClass) {
this.id = id;
this.oneClass = oneClass;
}
public InnerClass(int id){
this.id = id;
}
}
class oneClass {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
This is the class where the main method exists, observe that the package is different:
package trickycorejava.constructor;
import trickycorejava.InnerClass;
public class InnerClassTest {
public static void main(String[] args) {
InnerClass innerClass = new InnerClass(1);
}
}
How can I initialize the InnerClass with constructor in this case? If I use
InnerClass innerClass = new InnerClass(1, new oneClass("Test"));
I get the error that oneClass is not public cannot be access from outside package.
As Turing85 pointed out the oneClass should be in it's own file, otherwise it's going to be package-private which means you can only access it from classes of the same package.
Is there another way? There is, but it's not going to be a simple constructor call. Using reflection you can bypass class, field and method invocation protection.
public class InnerClassTest {
public static void main(String[] args) throws Exception {
Constructor<OneClass> constructor = OneClass.class.getDeclaredConstructor(String.class);
constructor.setAccessible(true);
OneClass instance = constructor.newInstance("John");
InnerClass innerClass = new InnerClass(1, instance);
}
}
What this does is that it finds the constructor that is private to Main because the class is package-private. Then it disables the protection of it, note that these are temporary, the Constructor object is a new reference and only allows the invocation via this reference.
But I don't recommend doing this extensively. Reflection has some use cases, mainly to aid programmers in frameworks like Spring, but otherwise it can break object oriented patterns.

I need help creating constructors and returning boolean and strings

I need help fixing my code with the basic concepts listed above. To save from clutter, I took a screen shot of the directions here: https://imgur.com/SdiotUi
However, when I run my code it isn't working. I know there are a lot of errors but I'm having trouble fixing them even though I've spent the past few hours googling the correct way to do this.
When I create the first constructors I am not sure if I am assigning the name and legs correctly, I am having trouble returning "true", I get an error calling the parent class taking one argument, and I don't think I am overriding the abstract class correctly.
My code:
public class Animal1 {
private String animalName;
public int numberOfLegs;
public Animal1(String name){
name = animalName;
name = "John";
}
public Animal1(String name, int legs){
name = animalName;
legs = numberOfLegs;
name = "Jack";
legs = 4;
}
public String getName(){
return animalName;
}
public int getLegs(){
return numberOfLegs;
}
public void isAMammal(){
return true;
}
public void isCarnivorous(){
return true;
}
public abstract class getHello{
}
}
public class Cat1 extends Animal1{
public Cat1(String name){
Animal1.name;
}
public abstract class getHello{
return "Meow";
}
}
public class Dog1 extends Animal1{
public Dog1(String name){
Animal1.name;
}
public abstract class getHello{
return "Woof";
}
}
public abstract class Animal1 { // If you want to have an abstract method, declare the class as abstract
private final String animalName;
private final int numberOfLegs; // better of using private and make it final since it's not going to change.
public Animal1(final String name, final int legs){ //better making the input parameters final since they are not supposed to be changed
//name = animalName;
//legs = numberOfLegs;//it assigned the field to an input parameter. that will take no effect on the object created.
animalName = name;
numberOfLegs = legs;
}
public String getName(){
return animalName;
}
public int getLegs(){
return numberOfLegs;
}
public boolean isAnimal(){ //boolean function needs a return type too!!
return true;
}
public boolean isCarnivorous(){
return true;
}
public abstract String getHello(); // an abstract method has same requirement as a normal method besides the abstract modifier. it will need a return type. And it ends with a semicolon
}
public class Cat1 extends Animal1{
public Cat1(final String name){
super(name, 4); //use super to call parent constructor
}
#Override
public String getHello(){
return "Meow";
}
}
public class Dog1 extends Animal1{
public Dog1(final String name){
super(name, 4);
}
#Override
public String getHello(){
return "Woof";
}
}
First, it looks like a few of your methods are declared as classes. I assume you wanted to make them abstract methods. They need to be changed to:
public abstract String getHello();
Note that abstract methods can only be declared in an abstract class. So, you need to redefine Animal1 as abstract.
public abstract class Animal1
Next, when you implement the abstract method, you define it as
public String getHello()
If you are using an IDE like Eclipse it will automatically offer to generate this method.
Finally, when using your constructor in your child classes like Cat1, you are trying to set "name" as if it was a static variable and bypassing the constructor you already had set for Animal1. The best way to correct this is to change the constructor in Cat1 and Dog1 to call the super constructor.
public Cat1(String name){
super(name);
}

How to access private data member outside the class?

I am trying to access the private data member of inner class outside the outer class.
Please help me?
You don't - that's the whole point of it being private.
The inner class can expose the data via a property, of course:
public class Outer {
public class Inner {
private final String name;
public Inner(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
}
public class Other {
public void foo() {
Outer outer = new Outer();
Outer.Inner inner = outer.new Inner("Foo");
// Can't access inner.name here...
System.out.println(inner.getName()); // But can call getName
}
}
... but if the inner class wants to keep it private, then you shouldn't try to access it.
Create public getter setter methods inside the inner class for private variables. Then create an object and call them to access private data. You can't directly access private data.
you cant access a private data. If ýou have other thoughts of accessing it use public getter method returning that private data.
you can access private data member using getter method ex
package pack;
import java.io.ObjectInputStream.GetField;
public class abc {
private int num = 2;
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
}
class otherClass {
public static void main(String[] args) {
abc obj = new abc();
System.out.println(obj.getNum());
}
}

Passing object as parameter for constructor

I have 3 classes. These classes are Class1, Parent and Child. I'm having some trouble to figure out how to write a constructor I need for my Child class.
public Class1
{
private String firstName;
private String lastName;
public Class1()
{
firstName="";
lastName="";
}
public Class1(String firstName, String lastName)
{
this.firstName=firstName;
this.lastName=lastName;
}
//Methods and stuff
}
public Parent
{
private Class1 class1;
private double number;
public Parent();
{
class1=new Class1();
number=0;
}
public Parent(Class1 c, double n)
{
Class1=c;
number=n;
}
//Methods and stuff
}
public Child extends Parent
{
private String string;
private Boolean boolean;
public Child(Class1 class1, double n, String s, Boolean b)
{
//Don't know how to get the Class1 part to work
//Don't know how to get the double to work
string=s;
boolean=b;
//Methods and stuff
}
I don't know how to write the code so that I can get my constructor to take the arguments like this:
new Child(new Class1("String", "String"), 10, "String", true);
I hope this helps clarify what my problem is.
Create Child constructor as
public Child(Class1 objClass1, double number, string str, boolean bool){
super(objClass1,number);
this.str=str;
this.bool=bool;
}
Create Parent constructor as
public Parent(Class1 objClass1, double number){
this.objClass1=objClass1;
this.number=number;
}
and you can called the child constructor as
Child objChild=new Child(new Class1(str1,str2),number,str,bool);
I'm not going to give you the code, because you've not given us enough information, but let's assume you've got a class structure like..
public class Parent
{
private String field;
public Parent(String field) {
this.field = field;
}
}
public class Child extends Parent {
private String field;
public Child(String field)
{
this.field = field;
}
}
What you can do is specify a constructor in your Child class that passes the variables up the inheritance chain, to your Parent class:
public Child(String field, String parentField)
{
super(parentField); // Calls the parent class.
this(field);
}
So what you've done there, is passed the parentField up to the Parent class, and you've called your existing constructor that accepts a single String parameter.
Apply this principle to your code and you'll get it in minutes.

Categories