This question already has answers here:
Initialize field before super constructor runs?
(7 answers)
Closed 4 years ago.
So, I'm trying to design a small base abstract class:
public abstract class BaseClass
{
abstract void reload();
protected BaseClass()
{
reload();
// schedule reload for every X minutes
}
}
Now, subclass:
class SubClass extends BaseClass
{
private int member = 5;
#Override
void reload()
{
member = 20;
}
}
Now, the problem I'm facing is that reload() method is called before the member is initialized. Thus, member is assigned 20 and afterwards, assigned with the value 5. (this is only an example of course, the actual code is different, but the same idea).
What is the best design for what I'm trying to achieve?
I want the order of the initialization to be - member assigned 5, and if reload() fails for some reason i want it to stay with the initial value. However in this code, 5 overrides the value of reload(). If I don't assign an initial value for the instance member, it works of course.
Is it possible what I'm asking?
Override the constructor and call reload() there but do not call super(), this might not be acceptable for other reasons :)
class SubClass {
private int member = 5;
public SubClass() {
reload();
}
...
}
You can use a builder to achieve that.
This way you can achieve full control.
public abstract class Foo {
public abstract void postConstruct();
public static void main(String[] args) {
Bar bar = Foo.build(Bar.class);
System.out.println(bar);
}
public static <T extends Foo> T build(Class<T> clazz) {
T obj;
try {
obj = clazz.newInstance();
obj.postConstruct();
return obj;
} catch (Exception e) {
throw new IllegalArgumentException(
"Class "+clazz.getName()+" is not a valid class",e);
}
}
}
public class Bar extends Foo {
int value = 10;
protected Bar() {
super();
}
public void postConstruct() {
value = 7;
}
#Override
public String toString() {
return "Bar [value=" + value + "]";
}
}
I have such a question: is it possible some how to "extract" superclass from one object to new object? I'll show what I mean.
public class test {
public static void main(String[] args) {
subclass sb = new subclass(false);
System.out.println(sb.a);
System.out.println(sb.b);
superclass sc = sb;
superclass sc2;
try {
sc2 = sc.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
return;
}
System.out.println(((subclass)sc2).a);
}
private static class superclass implements Serializable, Cloneable {
public boolean b;
public superclass() {
b = false;
}
public superclass(boolean a) {
this.b = a;
}
public superclass clone() throws CloneNotSupportedException {
return (superclass)super.clone();
}
}
private static class subclass extends superclass implements Serializable{
public boolean a;
public subclass(boolean a) {
super(true);
this.a = a;
}
}
}
with this code I'm getting this output:
false
true
false
which means that object was cloned totally, bu I want to clone only superclass.
Is it any already implemented way to do this or I have to implement my own field-to-field copy method in superclass?
Not sure what are you really trying to achive/prove by the example. Even if it was possible to clone only superclass, the result would still remain the same as it would simply just copy the a field.
Anyway, the answer is no. The clone is method by purpose so you don't need to care about the real class in the background. If you wished to do partial clone for specific super class you could easily achieve this by calling specific constructor/setters as you have all the information in compile time.
Im very new to programming and want to know if I can somehow get the object from a class where I already used new MyClass(); to use it in another class and that I don't need to use new MyClass(); again. Hope you get the point.
Some very simple example:
class MyFirstClass
{
Something st = new Something();
}
class Something()
{
// some code
}
class MySecondClass
{
// This is where I want to use the object from class Something()
// like
getObjectFromClass()
}
You can use Singleton pattern to achieve this
This is kickoff example of such object. It has a private constructor and public class method getInstance:
static methods, which have the static modifier in their declarations,
should be invoked with the class name, without the need for creating
an instance of the class
When we make a call to getInstance it checks if an object has been created already and will return an instance of already created objected, if it wasn't created it will create a new object and return it.
public class SingletonObject {
private static int instantiationCounter = 0; //we use this class variable to count how many times this object was instantiated
private static volatile SingletonObject instance;
private SingletonObject() {
instantiationCounter++;
}
public static SingletonObject getInstance() {
if (instance == null ) {
instance = new SingletonObject();
}
return instance;
}
public int getInstantiationCounter(){
return instantiationCounter;
}
}
To check how does this work you can use the following code:
public static void main(String[] args) {
SingletonObject object = SingletonObject.getInstance();
System.out.println("Object was instantiated: " + object.getInstantiationCounter() + " times.");
object = SingletonObject.getInstance();
System.out.println("Object was instantiated: " + object.getInstantiationCounter() + " times.");
object = SingletonObject.getInstance();
System.out.println("Object was instantiated: " + object.getInstantiationCounter() + " times.");
}
Since you have just started coding won't give you a term like reflection and all.. here is one of the simple way is have a public getter() method.
Consider this simple example
class Something {
private int a=10;
public int getA() {
return a;
}
}
Here is the First which has a public method which return the object that i created in this class for the Something Class
class MyFirstClass {
private Something st;
public MyFirstClass() {
this.st = new Something();
}
public Something getSt() {
return st;
}
}
Accessing it from another Class
class MySecondClass {
public static void main(String...strings ){
MyFirstClass my =new MyFirstClass();
System.out.println(my.getSt().getA());
}
}
Output: 10
If You wan't to verify
Inject this function in MyFirstClass
public void printHashcode(){
System.out.println(st);
}
and then print the hash codes from both methods in MySecondClass
class MySecondClass {
public static void main(String...strings ){
MyFirstClass my =new MyFirstClass();
System.out.println(my.getSt());
my.printHashcode();
}
}
You will see that indeed you are using the Object created in MyFirstClass in MySecondClass.
Because this will give you same hashcode output.
Output On my machine.
Something#2677622b
Something#2677622b
Instead of using the Singleton pattern, a better pattern to use is dependency injection. Essentially, you instantiate the class you want to share, and pass it in the constructor of every class that needs it.
public class MainClass {
public static void main(String[] args) {
SharedClass sharedClass = new SharedClass();
ClassA classA = new ClassA(sharedClass);
ClassB classB = new ClassB(sharedClass);
}
}
public class ClassA {
private SharedClass sharedClass;
public ClassA(SharedClass sharedClass) {
this.sharedClass = sharedClass;
}
}
public class ClassB {
private SharedClass sharedClass;
public ClassB(SharedClass sharedClass) {
this.sharedClass = sharedClass;
}
}
Singleton pattern lets you have single instance which is 'globally' accessible by other classes. This pattern will 'guarantee' that you have only one instance in memory. There are exceptions to one instance benefit, such as when deserializaing from file unless care is taken and readResolve is implemented.
Note that class Something right now has no state(fields), only behavior so it is safe to share between multiple threads. If Something had state, you would need to provide some kind of synchronization mechanism in multi thread environment.
Given such stateless Singleton, it would be better to replace it with class that contains only static methods. That is, unless you are implementing pattern such as Strategy which requires interface implementation, then it would be good idea to cache instance like bellow with Singleton pattern.
You should rework your Something class like this to achieve singleton:
public class Something {
private static final Something INSTANCE = new Something ();
private Something () {
// exists to defeat instantiation
}
public Something getInstance() {
return INSTANCE;
}
public void service() {
//...
}
public void anotherService() {
//..
}
}
If FirstClass and SecondClass are somehow related, you can extract that common object you're using to a super class, and that's the only scope in which you're planning to use this object.
public class SuperClass{
Something st = new Something();
public Something getObjectFromClass(){
return st;
}
}
public class MyFirstClass extends SuperClass{
getObjectFromClass();
}
public class MySecondClass extends SuperClass{
getObjectFromClass();
}
Otherwise, if you plan to use that instance somewhere else you should use a
Singleton object. The easiest way of doing this is:
enum Singleton
{
INSTANCE;
private final Something obj;
Singleton()
{
obj = new Something();
}
public Something getObject()
{
return obj;
}
}
You use it:
Singleton.INSTANCE.getObject();
Okay firstly you can use inheritance e.g.
class MyFirstClass
{
Something st = new Something();
}
class Something()
{
// some code
}
class MySecondClass extends myFirstClass
{
// This is where I want to use the object from class Something()
// like
MySecondClass obj = new MySecondClass();
obj.method(); //Method from myfirstclass accessible from second class object
}
Or if you dont want any objects and just the method you can implement interfaces e.g.
public interface MyFirstClass
{
//example method
public abstract void saying(); //no body required
Something st = new Something();
}
class Something()
{
// some code
}
class MySecondClass implements MyFirstClass //Have to implement methods
{
public void saying(){ //Method implemented from firstClass no obj
System.out.println("Hello World");
}
getObjectFromClass()
}
I created an instance of a class in java as following:
ABC ab = new ABC();
I want to access this instant ab in another class XYZ. How to make this Object available in class XYZ?
It is difficult to answer your question without more specific information about your problem, but this would certainly work:
You can use a setter to initialize an instance variable in your other class if you want to use it everywhere in that class:
class someClass {
void someMethod() {
ABC ab = new ABC();
XYZ xyz = new XYZ();
xyz.setABC(ab);
}
}
class XYZ {
ABC ab;
//...
void setABC(ABC ab) {
this.ab = ab;
}
//...
void doSomething() {
// do something with instance variable ab
}
}
There are several ways to do what you want to achieve. Some of them might be as follows:
Passing the object reference through a constructor
Here, you would explicitly pass the reference of your reference class when you're creating an object of the actual class.
public class ActualClass{
private ReferenceClass refClassObject;
/**
* Passing through a constructor
*/
public ActualClass(ReferenceClass refClassObject){
this.refClassObject = refClassObject;
}
}
class ReferenceClass{
/**
* Your implementation of the class
*/
}
Using getter/setter methods
In this approach, you would pass the reference of your object through explict public setXX() methods. This approach is more flexible because you can update the reference object as and when you want to (think polymorphism). As an example:
public class ActualClass{
private ReferenceClass refClassObject;
public ActualClass(){
}
public void setReferenceClass(ReferenceClass refClassObject){
this.refClassObject = refClassObject;
}
public ReferenceClass getReferenceClass(){
return refClassObject;
}
}
class ReferenceClass{
/**
* Your implementation of the class
*/
}
Using a combination of constructors and getters/setters
For added flexibility, you might want to initialize your Actual class object with a reference. However if you would also want to keep the option of changing the reference at object at a later stage, go for a combination of both #1 & #2 that I specified above.
public class ActualClass{
private ReferenceClass refClassObject;
public ActualClass(){
}
public ActualClass(ReferenceClass refClassObject){
this.refClassObject = refClassObject;
}
public void setReferenceClass(ReferenceClass refClassObject){
this.refClassObject = refClassObject;
}
public ReferenceClass getReferenceClass(){
return refClassObject;
}
}
class ReferenceClass{
/**
* Your implementation of the class
*/
}
Which one should you choose? Well it would depend on your implementation and requirement.
This answer is exactlty same as Doug Ramsey this link
I tried to explain with the same logic.
public class A {
public void m1() {
System.out.println("inside m1 method");
ABC ab = new ABC(); // 2 object is made and reference is given to ab
XYZ xyz = new XYZ(); 3 object is made and reference is given to xyz
xyz.send(ab); // 4 THIS IS WHAT YOUR QUESTION MEANS
}
}
class XYZ {
ABC ab;
//...
void send(ABC ab) { // 5
this.ab = ab;
System.out.println("inside send");
callme();
}
//...
void callme() { // 6
System.out.println("A is : "+ab.a);
System.out.println("b is : "+ab.b);
// do something with instance variable ab
}
}
public class ABC {
int a = 10;
static int b= 20;
public static void main(String[] args) // called first
{
A a = new A();
a.m1();
}
}
You have two ways to pass object parameter to one class to another.
Passing parameter to a method
public void passMethod(ABC ab) {
}
Passing parameter to a constructor
public class XYZ {
public XYZ(ABC ab) {
}
}
I know this question is old, but If I'm correct you want to transfer an Object into another class to be used.
In order to do that you need a few things
Class XYZ has to have a constructor to take in the parameter "Object" it would something like
class XYZ{
private Object ab
public XYZ(Object ab){
this.ab = ab;//This is the constructor called when you create an XYZ object, and want to use the Object ab in XYZ
}
package demo;
class ABC{
void disp(xyz arg1){
System.out.println("runing disp method in pratics");
System.out.println("x value:"+arg1.x);
arg1.test();
}
}
class xyz{
int x = 67;
void test(){
System.out.println("runing test method in pratics");
}
}
class pratics {
public static void main(String[] args) {
ABC ab=new ABC();
ab.disp(new xyz());
}
}
This is a question I was asked in an interview: I have class A with private members and Class B extends A. I know private members of a class cannot be accessed, but the question is: I need to access private members of class A from class B, rather than create variables with the same value in class B.
The interviewer was either testing your knowledge of access modifiers, or your approach to changing existing classes, or both.
I would have listed them (public, private, protected, package private) with an explanation of each. Then gone on to say that class A would need to be modified to allow access to those members from class B, either by adding setters and getters, or by changing the access modifiers of the members. Or class B could use reflection. Finally, talk about the pros and cons of each approach.
Reflection? Omitting imports, this should work:
public class A {
private int ii = 23;
}
public class B extends A {
private void readPrivateSuperClassField() throws Exception {
Class<?> clazz = getClass().getSuperclass();
Field field = clazz.getDeclaredField("ii");
field.setAccessible(true);
System.out.println(field.getInt(this));
}
public static void main(String[] args) throws Exception {
new B().readPrivateSuperClassField();
}
}
It'll not work if you do something like that before the of invocation readPrivateSuperClassField();:
System.setSecurityManager(new SecurityManager() {
#Override
public void checkMemberAccess(Class<?> clazz, int which) {
if (clazz.equals(A.class)) {
throw new SecurityException();
} else {
super.checkMemberAccess(clazz, which);
}
}
});
And there are other conditions under which the Reflection approach won't work. See the API docs for SecurityManager and AccessibleObject for more info. Thanks to CPerkins for pointing that out.
I hope they were just testing your knowledge, not looking for a real application of this stuff ;-) Although I think an ugly hack like this above can be legit in certain edge cases.
The architecture is broken. Private members are private because you do not want them accessed outside the class and friends.
You can use friend hacks, accessors, promote the member, or #define private public (heh). But these are all short term solutions - you will probably have to revisit the broken architecture at some stage.
By using public accessors (getters & setters) of A's privates members ...
You cannot access private members from the parent class. You have make it protected or have protected/public method that has access to them.
EDIT : It is true you can use reflection. But that is not usual and not good idea to break encapsulation.
A nested class can access to all the private members of its enclosing class—both fields and methods. Therefore, a public or protected nested class inherited by a subclass has indirect access to all of the private members of the superclass.
public class SuperClass
{
private int a = 10;
public void makeInner()
{
SubClass in = new SubClass();
in.inner();
}
class SubClass
{
public void inner()
{
System.out.println("Super a is " + a);
}
}
public static void main(String[] args)
{
SuperClass.SubClass s = new SuperClass().new SubClass();
s.inner();
}
}
If I'm understanding the question correctly, you could change private to protected. Protected variables are accessible to subclasses but behave like private variables otherwise.
By using setters and getters u can access it
From JLS §8.3. Field Declarations:
A private field of a superclass might be accessible to a subclass - for example, if both classes are members of the same class. Nevertheless, a private field is never inherited by a subclass.
I write the example code:
public class Outer
{
class InnerA
{
private String text;
}
class InnerB extends InnerA
{
public void setText(String text)
{
InnerA innerA = this;
innerA.text = text;
}
public String getText()
{
return ((InnerA) this).text;
}
}
public static void main(String[] args)
{
final InnerB innerB = new Outer().new InnerB();
innerB.setText("hello world");
System.out.println(innerB.getText());
}
}
The explanation of the accessibility of InnerA.text is here JLS §6.6.1. Determining Accessibility:
Otherwise, the member or constructor is declared private, and access is permitted if and only if it occurs within the body of the top level class (§7.6) that encloses the declaration of the member or constructor.
You can use the setters and getters of class A. Which gives same feeling as if You are using a class A's object.
Have you thought about making them protected ? Just to be sure you are aware of this option, if you are then pardon me for bringing up this trivia ;)
Private members cant be accessed in derived class
If you want to access means you can use getter and setter methods.
class A
{
private int a;
void setA(int a)
{
this.a=a;
}
int getA()
{
return a;
}
}
Class B extends A
{
public static void main(String[] arg)
{
B obj= new B();
obj.setA(10);
System.out.println("The value of A is:"+obj.getA());
}
}
Private will be hidden until you have been given the right access to it. For instance Getters or setters by the programmer who wrote the Parent. If they are not visible by that either then accept the fact that they are just private and not accessible to you. Why exactly you want to do that??
I don't know about Java, but in some languages nested types can do this:
class A {
private string someField;
class B : A {
void Foo() {
someField = "abc";
}
}
}
Otherwise, use an accessor method or a protected field (although they are often abused).
A private member is accessible in subclass in a way that you cannot change the variable, but you are able to access the variable as read only.
Obviously, making them protected, or adding setters/getters is the preferred technique. Reflection is a desperation option.
Just to show off to the interviewer, IF "access" means read access, and IF Class A generates XML or JSON etc., you could serialize A and parse the interesting fields.
Class A
{
private int i;
int getValue()
{
return i;
}
}
class B extends A
{
void getvalue2()
{
A a1= new A();
sop(a1.getValue());
}
}
To access private variables of parent class in subclass you can use protected or add getters and setters to private variables in parent class..
You can't access directly any private variables of a class from outside directly.
You can access private member's using getter and setter.
Ways to access the superclass private members in subclass :
If you want package access just change the private fields to protected. It allows access to same package subclass.
If you have private fields then just provide some Accessor Methods(getters) and you can access them in your subclass.
You can also use inner class e.g
public class PrivateInnerClassAccess {
private int value=20;
class InnerClass {
public void accessPrivateFields() {
System.out.println("Value of private field : " + value);
}
}
public static void main(String arr[])
{
PrivateInnerClassAccess access = new PrivateInnerClassAccess();
PrivateInnerClassAccess.InnerClass innerClass = access.new InnerClass();
innerClass.accessPrivateFields();
}
}
4 .You can also use Reflection e.g
public class A {
private int value;
public A(int value)
{
this.value = value;
}
}
public class B {
public void accessPrivateA()throws Exception
{
A a = new A(10);
Field privateFields = A.class.getDeclaredField("value");
privateFields.setAccessible(true);
Integer value = (Integer)privateFields.get(a);
System.out.println("Value of private field is :"+value);
}
public static void main(String arr[]) throws Exception
{
B b = new B();
b.accessPrivateA();
}
}
You can use Accessors (getter and setter method) in your Code.
By using setter method you can use else with the help of refection you can use private member of class by setting that member say a -
take a from class
and set a.setAccessible(true);
You may want to change it to protected.
Kindly refer this
https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
If this is something you have to do at any cost just for the heck of doing it you can use reflection. It will give you list of all the variables defined in the class- be it public, private or protected. This surely has its overhead but yes, it is something which will let you use private variables. With this, you can use it in any of the class. It does not have to be only a subclass
Please refer to the example below. This may have some compilation issues but you can get the basic idea and it works
private void getPropertiesFromPrivateClass(){
Field[] privateVariablesArray = PrivateClassName.getClass().getDeclaredFields();
Set<String> propertySet = new HashSet<String>();
Object propertyValue;
if(privateVariablesArray.length >0){
for(Field propertyVariable :privateVariablesArray){
try {
if (propertyVariable.getType() == String.class){
propertyVariable.setAccessible(true);
propertyValue = propertyVariable.get(envtHelper);
System.out.println("propertyValue");
}
} catch (IllegalArgumentException illegalArgumentException) {
illegalArgumentException.printStackTrace();
} catch (IllegalAccessException illegalAccessException) {
illegalAccessException.printStackTrace();
}
}
Hope this be of some help.
Happy Learning :)
Below is the example for accessing the private members of superclass in the object of subclass.
I am using constructors to do the same.
Below is the superclass Fruit
public class Fruit {
private String type;
public Fruit() {
}
public Fruit(String type) {
super();
this.type = type;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
Below is subclass Guava which is inheriting from Fruit
public class Guava extends Fruit{
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Guava(String name,String type) {
super(type);
this.name=name;
}
}
Below is the main function where we are creating an object of subclass and also displaying the member of superclass.
public class Main {
public static void main(String[] args) {
Guava G1=new Guava("kanpuria", "red");
System.out.println(G1.getName()+" "+G1.getType());
}
}
Note that a private field of a superclass might be accessible to a subclass (for example,if both classes are memebers of the same class),Nevertheless,a private field is never inherited
by a subclass
Simple!!!
public class A{
private String a;
private String b;
//getter and setter are here
}
public class B extends A{
public B(String a, String b){ //constructor
super(a,b)//from here you got access with private variable of class A
}
}
thanks
Directly we can't access it. but Using Setter and Getter we can access,
Code is :
class AccessPrivate1 {
private int a=10; //private integer
private int b=15;
int getValueofA()
{
return this.a;
}
int getValueofB()
{
return this.b;
}
}
public class AccessPrivate{
public static void main(String args[])
{
AccessPrivate1 obj=new AccessPrivate1();
System.out.println(obj.getValueofA()); //getting the value of private integer of class AccessPrivate1
System.out.println(obj.getValueofB()); //getting the value of private integer of class AccessPrivate1
}
}
Modifiers are keywords that you add to those definitions to change their meanings. The Java language has a wide variety of modifiers, including the following:
Java Access Modifiers
Non Access Modifiers
To use a modifier, you include its keyword in the definition of a class, method, or variable. The modifier precedes the rest of the statement.
There is more information here:
http://tutorialcorejava.blogspot.in/p/java-modifier-types.html