Access object from another class to get its variable - java

I got the object wolfOne of the Class Wolf, and I need to access to its variable mAlive in another Class, how may I don it?
Wolf wolfOne;
//Wolf Class
public class Wolf extends Card {
public Wolf(){
mCharacter = "Wolf";
}
public void savage(Card card) {
card.mAlive = false;
}
}
//Card Class
public class Card {
//Names
public String mCharacter;
//Status
public static boolean mAlive;
public static boolean mDefended;
public static boolean mOwled;
public static boolean mLastSavaged;
public static boolean mLastLynched;
//Constructor
public Card() {
// Do Card specific stuff.
}
}

Remove static from all of your Class variables - make them instance variables instead. Then provide typical getters/setters for each, allowing clients of the class to retrieve or mutate the value:
public class Wolf extends Card {
public Wolf(){
setMCharacter("Wolf");
}
public void savage(Card card) {
card.setMAlive(false);
}
}
public class Card {
//Names
private String mCharacter;
//Status
private boolean mAlive;
private boolean mDefended;
private static boolean mOwled;
private static boolean mLastSavaged;
private static boolean mLastLynched;
public String getMCharacter(){}
return mCharacter;
}
public void setMCharacter(String value){
this.mCharacter = value;
}
public boolean getMAlive(){
return mAlive;
}
public void setMAlive(boolean alive){
this.mAlive = alive
}
//....So on and so forth
}

static has a special meaning in Java. It doesn't mean that the variable or method is inheritable; it means that there is only one of it that belongs to the class, not the instance.
To inherit from a super class, all that is required is that it not private and the inheriting classes will get it. The following example shows this relationship.
import java.util.*;
import java.lang.*;
import java.io.*;
class A
{
public String name;
public boolean isAlive;
public A()
{
name = "A";
isAlive = true;
}
}
class B extends A
{
public B()
{
name = "B";
isAlive = false;
}
}
public class Main
{
public static void main (String[] args)
{
A a = new A();
A b1 = new B();
B b2 = new B();
b2.name = "B2";
b2.isAlive = true;
System.out.println(a.name);
System.out.println(a.isAlive);
System.out.println(b1.name);
System.out.println(b1.isAlive);
System.out.println(b2.name);
System.out.println(b2.isAlive);
}
}
And gives this output:
A
true
B
false
B2
true
This can be run here.

In the card class make the fields private not public, in oo this is called encapsulation or data hiding (look it up). Then simply add a getMAlive method that returns the mAlive value and a setMAlive method which will set it. Now in your wolf class to set mAlive you can with setMAlive(boolean). For external objects you will need to have a reference to your wolf/card and call wolfName.getMAlive()
For card...
private boolean mAlive;
public boolean getMAlive(){
return mAlive;
}
public void setMAlive(boolean value){
mAlive = value;
}
For wolf...
public void savage(){
setMAlive(false);
}
For other classes to get mAlive...
wolfName.getMAlive()
You may consider making your mAlive (and other fields in Card) protected. Protected fields can only be seen by those classes that extend them e.g. wolf. So in wolfs savage method you could do...
public void savage(){
mAlive = false;
}
But to set mAlive from other classes you would still need a setter in Card so yeah
I hope this helps :) good luck

Related

Java visible interface that can not be implemented

I'm working on making a programming language that compiles to JVM bytecode, and it highly relies on interfaces as types. I need some way to make an interface private, but have other code still be able to access it, but not make something that implements it.
I was thinking about using abstract classes with a private constructor, so only the classes in the same file would be able to access it. The only problem is that it is impossible to extend multiple abstract classes at once. For example, the structure of a simple compiled program would be this:
// -> Main.java
public class Main {
public static MyInteger getMyInteger() {
return new MyIntegerImpl(10);
}
public static void main(String[] args) {}
private interface MyInteger {
public int getValue();
}
private static class MyIntegerImpl implements MyInteger {
private final int value;
public int getValue() {
return value;
}
public MyIntegerImpl(int value) {
this.value = value;
}
}
}
And another file, in which there is a problem:
// -> OtherFile.java
public class OtherFile {
public static void main(String[] args) {
Main.MyInteger myInteger = Main.getMyInteger(); //Error: The type Main.MyInteger is not visible.
System.out.println(myInteger.getValue());
}
//I do not want this to be allowed
public static class sneakyInteger implements Main.MyInteger { //Error(Which is good)
public int getValue() {
System.out.println("Person accessed value");
return 10;
}
}
}
The reason why I want to do this is so one person can not mess up any other person's code by providing their own implementations of things that should be only implemented by that other person.
Any help would be much appreciated.
I'm pretty sure that you should think again about what you are trying to do and change approach, but the answer for your question is to add to the interface some empty void method that is getting the parameter of the inner private class specific for the wrapper class
public class Test {
private class InnerPrivateClass {
private InnerPrivateClass() {}
}
public interface MyInteger {
int getValue();
void accept(InnerPrivateClass c);
}
private class MyIntegerImpl implements MyInteger {
#Override
public int getValue() {
return 0;
}
#Override
public void accept(InnerPrivateClass c) {}
}
}
However, as I said, I don't like this and for me it means that your idea is broken

Accessibility between objects (instances) of the same class

When one object of a class has a reference to another object of
the same class, the first object can access all the second object’s
data and methods (including those that are private).
I took this sentence from a book. But I couldn't figure out actually what it means.
It means that private members are visible to other instances of the same class. For example:
class A {
private int v;
public boolean isSameV(A other) {
return this.v == other.v; // can acccess other.v
}
}
It means that if you have a class that looks like this
public class A {
private int number;
private A otherInstance;
public int number2;
public void DoStuff() {
...
}
}
you can access A.number in the DoStuff method (or any other class method) even although number is actually private.
e.g.
public class A {
...
public void DoStuff() {
this.otherInstance.number = 42;
^^^^^^^
cannot access private members here
}
}
is perfectly fine, while
public class B {
private A aInstance;
public void DoStuffToo() {
this.aInstance.number = 42;
}
}
would not compile, because B cannot access A's private members.
Good question actually, I faced similar problem when I started learning Java, here is how it looks in practice:
public class A {
private String example;
protected int anotherOne;
public A(){
}
public A(A a){
this.example = a.example; // here we get access to private member of another object of same class
this.anotherOne = a.anotherOne; // it works for protected as well
}
// This works for methods not just constructor, lets consider we want to swap value of example:
public void swapExample(A a){
String temp = a.example;
a.example = this.example;
this.example = temp;
}
}
Private fields can be accessed from inside of the class, by this construction you can access all the field of an instance of Foo without getters and setters when you are in class Foo :
public class Foo {
private String name;
public int sumLetter(Foo b) {
return this.name.length() + b.name.length();
}
}
The doc : Declaring Member Variables :
private modifier — the field is accessible only within its own class.

When creating a builder with a superclass, parent cannot return instance of child class [duplicate]

This question already has answers here:
Subclassing a Java Builder class
(10 answers)
Closed 6 years ago.
If I am using the builder pattern to configure new objects I may have two classes like Game and HockeyGame (shown below). When I want to create a new HockeyGame, I get it's builder and start calling methods to configure the object as needed.
The problem I am running into is shown in the main function. Once I call one method from the super class it returns as an intance of Game.Builder, and I can no longer call any method from the child class.
What is the best way to deal with this?
Main.java
class Main {
public static void main(String[] args){
HockeyGame hg = new HockeyGame.Builder()
.setScore(5)
.setTimeLimit(3600)
//--------------------------------------------------------------------
.setIceTemperature(-5) // Error! Cannot call setIceTempurature() on
// an instance of Game.Builder
//--------------------------------------------------------------------
.build();
}
}
Game.java
public class Game{
int score;
int timeLimit;
public Game(int score, int timeLimit) {
this.score = score;
this.timeLimit = timeLimit;
}
public static class Builder {
int score;
int timeLimit;
public Builder setScore(int score) {
this.score = score;
return this;
}
public Builder setTimeLimit(int timeLimit) {
this.timeLimit = timeLimit;
return this;
}
public Game build() {
return new Game(score, timeLimit);
}
}
}
HockeyGame.java
public class HockeyGame extends Game {
float iceTemperature;
public HockeyGame(int score, int timeLimit, float iceTemperature) {
super(score, timeLimit);
this.iceTemperature = iceTemperature;
}
public static class Builder extends Game.Builder {
float iceTemperature;
public HockeyGame.Buidler setIceTemperature(float iceTemperature) {
this.iceTemperature = iceTemperature;
return this;
}
public HockeyGame build(){
return new HockeyGame(score, timeLimit, iceTemperature);
}
}
}
Thanks.
You need to use the getThis() trick that is prevalent in much fluent API code.
First you need to make your Game.Builder generic in itself:
public static class Builder<B extends Builder<B>>
Then you add a getThis() method:
public B getThis() {
return (B) this;
}
Now you change your setters to return a B and return getThis() rather than this:
public B setTimeLimit(int timeLimit) {
//...
return getThis();
}
Your extension class also needs to be generic, in itself:
public static class Builder<B extends Builder<B>> extends Game.Builder<B>
Now you can use the code, and it will "remember" the intended type:
HockeyGame hockeyGame = new HockeyGame.Builder<>().setScore(10)
.setTimeLimit(20)
.setIceTemperature(-1)
.build();
This final code looks something like:
public class Game {
private final int score;
private final int timeLimit;
private Game(final Builder<?> builder) {
this.score = builder.score;
this.timeLimit = builder.timeLimit;
}
public static class Builder<B extends Builder<B>> {
private int score;
private int timeLimit;
public B setScore(int score) {
this.score = score;
return getThis();
}
public B setTimeLimit(int timeLimit) {
this.timeLimit = timeLimit;
return getThis();
}
protected B getThis() {
return (B) this;
}
public Game build() {
return new Game(this);
}
}
}
public class HockeyGame extends Game {
private final float iceTemperature;
private HockeyGame(final Builder<?> builder) {
super(builder);
this.iceTemperature = builder.iceTemperature;
}
public static class Builder<B extends Builder<B>> extends Game.Builder<B> {
private float iceTemperature;
public B setIceTemperature(float iceTemperature) {
this.iceTemperature = iceTemperature;
return getThis();
}
#Override
public HockeyGame build() {
return new HockeyGame(this);
}
}
}
N.B: I have made the fields private final and also the main type constructors - this forces people to use the Builder. Also, the constructor can take a Builder<?> and copy the variable from there - this tidies the code a little.
The actual hack is, as you may have noticed, here:
public B getThis() {
return (B) this;
}
Here, we force a cast of the Builder to its generic type - this allows us to change the return type of the method dependant upon the specific instance being used. The issue is, if you declare a new Builder something like the following:
public static class FootballGame extends Game {
private FootballGame(final Builder<?> builder) {
super(builder);
}
public static class Builder<B extends HockeyGame.Builder<B>> extends Game.Builder<B> {
float iceTemperature;
#Override
public FootballGame build() {
return new FootballGame(this);
}
}
}
This this will blow up at runtime with a ClassCastException. But the setter method will return a HockeyGame.Builder rather than FootballGame.Builder so the issue should be obvious.
Try something like this
You explicitely cast it back to a HockeyGame.Builder object and work with its own method(s) on it.
The problem you had is that setTimeLimit returns a Builder object (mother class) and so you can not use the child methods on it.
HockeyGame hg = ((HockeyGame.Builder)(new HockeyGame.Builder().setScore(5)
.setTimeLimit(3600)))
.setIceTemperature(-5)
.build();
Also, setIceTemparature should return a HockeyGame.Builder object to be able to build on it.
public Builder setIceTemperature(float iceTemperature) {
this.iceTemperature = iceTemperature;
return this;
}

Permanent change of a variable in static method

Let's say I have a public class with static methods, one of them for example:
public static void test(boolean b){
b = !b;
}
Let's say this class name is Test. From another class, where I have a variable boolean a = false, I call
Test.test(a);
How can I make it change a permanently, and not just change it in that static methods scope?
The only way to make the change permanent is to let the method have a return value and assign it to the variable :
public static boolean test(boolean b){
return !b;
}
a = Test.test(a);
Sounds to me like you are looking for a Mutable Boolean, the simplest of which is an AtomicBoolean.
private void changeIt(AtomicBoolean b) {
b.set(!b.get());
}
public void test() {
AtomicBoolean b = new AtomicBoolean(false);
changeIt(b);
System.out.println(b);
}
Use a static field:
public static boolean flag;
public static void test(boolean b){
flag = !b;
}
Then:
boolean a = true;
Test.test(a);
System.out.println( Test.flag); // false
You can pass an instance to method and use setters to change more variables at once.
public static void updateData(MyClass instance) {
instance.setX(1);
instance.setY(2);
}
in your Test class you can define the boolean variable as static
public static boolean a;
and outside the class change or access it using Test.a=false; or a=Test.a
and if you need to use methods you can hide the static method with inheritance:
public class HideStatic {
public static void main(String...args){
BaseA base = new ChildB();
base.someMethod();
}
}
class BaseA {
public static void someMethod(){
System.out.println("Parent method");
}
}
class ChildB extends BaseA{
public void someMethod(){
System.out.println("Child method");
}
}
I think you are asking for call by reference. You can get this in Java by using arrays:
public static void test(boolean[] b){
b[0] = !b[0];
}
boolean[] param = new boolean[] {a};
test(param);
a=param[0];
//a changed
This works, but it is ugly. If you need to return more than one value, have a look at the Pair or Tuple structures.

Is there a way to override class variables in Java?

class Dad
{
protected static String me = "dad";
public void printMe()
{
System.out.println(me);
}
}
class Son extends Dad
{
protected static String me = "son";
}
public void doIt()
{
new Son().printMe();
}
The function doIt will print "dad". Is there a way to make it print "son"?
In short, no, there is no way to override a class variable.
You do not override class variables in Java you hide them. Overriding is for instance methods. Hiding is different from overriding.
In the example you've given, by declaring the class variable with the name 'me' in class Son you hide the class variable it would have inherited from its superclass Dad with the same name 'me'. Hiding a variable in this way does not affect the value of the class variable 'me' in the superclass Dad.
For the second part of your question, of how to make it print "son", I'd set the value via the constructor. Although the code below departs from your original question quite a lot, I would write it something like this;
public class Person {
private String name;
public Person(String name) {
this.name = name;
}
public void printName() {
System.out.println(name);
}
}
The JLS gives a lot more detail on hiding in section 8.3 - Field Declarations
Yes. But as the variable is concerned it is overwrite (Giving new value to variable. Giving new definition to the function is Override). Just don't declare the variable but initialize (change) in the constructor or static block.
The value will get reflected when using in the blocks of parent class
if the variable is static then change the value during initialization itself with static block,
class Son extends Dad {
static {
me = "son";
}
}
or else change in constructor.
You can also change the value later in any blocks. It will get reflected in super class
Yes, just override the printMe() method:
class Son extends Dad {
public static final String me = "son";
#Override
public void printMe() {
System.out.println(me);
}
}
You can create a getter and then override that getter. It's particularly useful if the variable you are overriding is a sub-class of itself. Imagine your super class has an Object member but in your sub-class this is now more defined to be an Integer.
class Dad
{
private static final String me = "dad";
protected String getMe() {
return me;
}
public void printMe()
{
System.out.println(getMe());
}
}
class Son extends Dad
{
private static final String me = "son";
#Override
protected String getMe() {
return me;
}
}
public void doIt()
{
new Son().printMe(); //Prints "son"
}
If you are going to override it I don't see a valid reason to keep this static. I would suggest the use of abstraction (see example code). :
public interface Person {
public abstract String getName();
//this will be different for each person, so no need to make it concrete
public abstract void setName(String name);
}
Now we can add the Dad:
public class Dad implements Person {
private String name;
public Dad(String name) {
setName(name);
}
#Override
public final String getName() {
return name;
}
#Override
public final void setName(String name) {
this.name = name;
}
}
the son:
public class Son implements Person {
private String name;
public Son(String name) {
setName(name);
}
#Override
public final String getName() {
return name;
}
#Override
public final void setName(String name) {
this.name = name;
}
}
and Dad met a nice lady:
public class StepMom implements Person {
private String name;
public StepMom(String name) {
setName(name);
}
#Override
public final String getName() {
return name;
}
#Override
public final void setName(String name) {
this.name = name;
}
}
Looks like we have a family, lets tell the world their names:
public class ConsoleGUI {
public static void main(String[] args) {
List<Person> family = new ArrayList<Person>();
family.add(new Son("Tommy"));
family.add(new StepMom("Nancy"));
family.add(new Dad("Dad"));
for (Person person : family) {
//using the getName vs printName lets the caller, in this case the
//ConsoleGUI determine versus being forced to output through the console.
System.out.print(person.getName() + " ");
System.err.print(person.getName() + " ");
JOptionPane.showMessageDialog(null, person.getName());
}
}
}
System.out Output : Tommy Nancy Dad
System.err is the same as above(just has red font)
JOption Output: Tommy then Nancy then Dad
This looks like a design flaw.
Remove the static keyword and set the variable for example in the constructor. This way Son just sets the variable to a different value in his constructor.
Though it is true that class variables may only be hidden in subclasses, and not overridden, it is still possible to do what you want without overriding printMe () in subclasses, and reflection is your friend. In the code below I omit exception handling for clarity. Please note that declaring me as protected does not seem to have much sense in this context, as it is going to be hidden in subclasses...
class Dad
{
static String me = "dad";
public void printMe ()
{
java.lang.reflect.Field field = this.getClass ().getDeclaredField ("me");
System.out.println (field.get (null));
}
}
https://docs.oracle.com/javase/tutorial/java/IandI/hidevariables.html
It's called Hiding Fields
From the link above
Within a class, a field that has the same name as a field in the superclass hides the superclass's field, even if their types are different. Within the subclass, the field in the superclass cannot be referenced by its simple name. Instead, the field must be accessed through super, which is covered in the next section. Generally speaking, we don't recommend hiding fields as it makes code difficult to read.
class Dad
{
protected static String me = "dad";
public void printMe()
{
System.out.println(me);
}
}
class Son extends Dad
{
protected static String _me = me = "son";
}
public void doIt()
{
new Son().printMe();
}
... will print "son".
It indeed prints 'dad', since the field is not overridden but hidden. There are three approaches to make it print 'son':
Approach 1: override printMe
class Dad
{
protected static String me = "dad";
public void printMe()
{
System.out.println(me);
}
}
class Son extends Dad
{
protected static String me = "son";
#override
public void printMe()
{
System.out.println(me);
}
}
public void doIt()
{
new Son().printMe();
}
Approach 2: don't hide the field and initialize it in the constructor
class Dad
{
protected static String me = "dad";
public void printMe()
{
System.out.println(me);
}
}
class Son extends Dad
{
public Son()
{
me = "son";
}
}
public void doIt()
{
new Son().printMe();
}
Approach 3: use the static value to initialize a field in the constructor
class Dad
{
private static String meInit = "Dad";
protected String me;
public Dad()
{
me = meInit;
}
public void printMe()
{
System.out.println(me);
}
}
class Son extends Dad
{
private static String meInit = "son";
public Son()
{
me = meInit;
}
}
public void doIt()
{
new Son().printMe();
}
Variables don't take part in overrinding. Only methods do. A method call is resolved at runtime, that is, the decision to call a method is taken at runtime, but the variables are decided at compile time only. Hence that variable is called whose reference is used for calling and not of the runtime object.
Take a look at following snippet:
package com.demo;
class Bike {
int max_speed = 90;
public void disp_speed() {
System.out.println("Inside bike");
}
}
public class Honda_bikes extends Bike {
int max_speed = 150;
public void disp_speed() {
System.out.println("Inside Honda");
}
public static void main(String[] args) {
Honda_bikes obj1 = new Honda_bikes();
Bike obj2 = new Honda_bikes();
Bike obj3 = new Bike();
obj1.disp_speed();
obj2.disp_speed();
obj3.disp_speed();
System.out.println("Max_Speed = " + obj1.max_speed);
System.out.println("Max_Speed = " + obj2.max_speed);
System.out.println("Max_Speed = " + obj3.max_speed);
}
}
When you run the code, console will show:
Inside Honda
Inside Honda
Inside bike
Max_Speed = 150
Max_Speed = 90
Max_Speed = 90
only by overriding printMe():
class Son extends Dad
{
public void printMe()
{
System.out.println("son");
}
}
the reference to me in the Dad.printMe method implicitly points to the static field Dad.me, so one way or another you're changing what printMe does in Son...
You cannot override variables in a class. You can override only methods. You should keep the variables private otherwise you can get a lot of problems.
No. Class variables(Also applicable to instance variables) don't exhibit overriding feature in Java as class variables are invoked on the basis of the type of calling object. Added one more class(Human) in the hierarchy to make it more clear. So now we have
Son extends Dad extends Human
In the below code, we try to iterate over an array of Human, Dad and Son objects, but it prints Human Class’s values in all cases as the type of calling object was Human.
class Human
{
static String me = "human";
public void printMe()
{
System.out.println(me);
}
}
class Dad extends Human
{
static String me = "dad";
}
class Son extends Dad
{
static String me = "son";
}
public class ClassVariables {
public static void main(String[] abc) {
Human[] humans = new Human[3];
humans[0] = new Human();
humans[1] = new Dad();
humans[2] = new Son();
for(Human human: humans) {
System.out.println(human.me); // prints human for all objects
}
}
}
Will print
human
human
human
So no overriding of Class variables.
If we want to access the class variable of actual object from a reference variable of its parent class, we need to explicitly tell this to compiler by casting parent reference (Human object) to its type.
System.out.println(((Dad)humans[1]).me); // prints dad
System.out.println(((Son)humans[2]).me); // prints son
Will print
dad
son
On how part of this question:- As already suggested override the printMe() method in Son class, then on calling
Son().printMe();
Dad's Class variable "me" will be hidden because the nearest declaration(from Son class printme() method) of the "me"(in Son class) will get the precedence.
Just Call super.variable in sub class constructor
public abstract class Beverage {
int cost;
int getCost() {
return cost;
}
}`
public class Coffee extends Beverage {
int cost = 10;
Coffee(){
super.cost = cost;
}
}`
public class Driver {
public static void main(String[] args) {
Beverage coffee = new Coffee();
System.out.println(coffee.getCost());
}
}
Output is 10.
Of course using private attributes, and getters and setters would be the recommended thing to do, but I tested the following, and it works... See the comment in the code
class Dad
{
protected static String me = "dad";
public void printMe()
{
System.out.println(me);
}
}
class Son extends Dad
{
protected static String me = "son";
/*
Adding Method printMe() to this class, outputs son
even though Attribute me from class Dad can apparently not be overridden
*/
public void printMe()
{
System.out.println(me);
}
}
class Tester
{
public static void main(String[] arg)
{
new Son().printMe();
}
}
Sooo ... did I just redefine the rules of inheritance or did I put Oracle into a tricky situation ?
To me, protected static String me is clearly overridden, as you can see when you execute this program. Also, it does not make any sense to me why attributes should not be overridable.
Why would you want to override variables when you could easily reassign them in the subClasses.
I follow this pattern to work around the language design. Assume a case where you have a weighty service class in your framework which needs be used in different flavours in multiple derived applications.In that case , the best way to configure the super class logic is by reassigning its 'defining' variables.
public interface ExtensibleService{
void init();
}
public class WeightyLogicService implements ExtensibleService{
private String directoryPath="c:\hello";
public void doLogic(){
//never forget to call init() before invocation or build safeguards
init();
//some logic goes here
}
public void init(){}
}
public class WeightyLogicService_myAdaptation extends WeightyLogicService {
#Override
public void init(){
directoryPath="c:\my_hello";
}
}

Categories