reference variables and objects - oop

I wanted to know why this did not work, as in why didn't the compiler invoke the restart method within the computer class...
Consider the following scenario:
I have 3 classes as shown below:
public class Computer {
public int compStatus = 0; //0 means off, 1 means on.
public void turnOn(){
this.compStatus = 1;
}
public void turnOff(){
this.compStatus = 0;
}
public void restart(){
if(compStatus ==1){
System.out.println("Turning off");
compStatus = 0;
System.out.println("Turning on");
compStatus = 1;
System.out.println("Restart successful");
}
}
}
Now the sub-class:
public class Macintosh extends Computer {
public void openXCode(){
if(compStatus == 1){
System.out.println("XCode Compiler opened.");
}
else{
System.out.println("Mac is off.");
}
}
public void restart(){
System.out.println("Mac restarted");
}
}
The tester class:
public class CompTest {
public static void main(String[] args){
Computer testObj = new Macintosh();
testObj.turnOn();
testObj.restart(); ///ERROR HERE
}
}
I am aware that the compiler checks if the restart method is in the class of the reference variable 'Computer' not the class of the actual object at the other end of the reference 'macintosh'. So if what I have said is true, why is the restart method not invoked?

You have to call the base class method in order to actually restart. Your method is just hiding the base method. You should override the method and then call it base.restart to do what you want.

Related

Pointcut for classes inside different package or sub-packages marked Deprecated and at the time whenever they used or instantiated?

I want to write a point cut for class instantiation in various packages,like classes inside the subpackages inside com.kepler.xenon (eg.com.kepler.xenon.modules.ticklers.pojo.Tickler,
com.kepler.xenon.modules.product.pojo.Product etc).
//This is my advice
#Aspect
#Component
public class OxAspect {
#After("execution(* com.oxane.xenon..*new(..)) && #within(java.lang.Deprecated)")
public void myAdvice(final JoinPoint jp){
System.out.println(jp.getSignature().getName()+""+jp.getTarget().getClass());
}
}
//This is my class
package com.kepler.xenon.modules.ticklers.pojo;
#Deprecated
public Class Ticklers{
#Id
#TableGenerator(name = "TICKLERS_ID", table = "ID_GENERATOR", pkColumnName = "GEN_KEY", valueColumnName = "GEN_VALUE", pkColumnValue = "TICKLERS_ID", allocationSize = 1, initialValue = 1)
#GeneratedValue(strategy = GenerationType.TABLE, generator = "TICKLERS_ID")
#Column(name = "TICKLERS_ID", unique = true, nullable = false)
private int ticklersId;
#Column(name = "TASK", nullable = false, length = 256)
private String taskName;
public int getTicklersId() {
return ticklersId;
}
public void setTicklersId(int ticklersId) {
this.ticklersId = ticklersId;
}
public String getTaskName() {
return taskName;
}
public void setTaskName(String taskName) {
this.taskName = taskName;
}
}
What i want is that if anyone tries to access the class which is deprecated,then pointcut filters that call and triggers advice.
I have done it for methods but i am failing to do it for classes.
I am adding aspect which works for methods,controller and Dao
#Aspect
#Component
public class OxAspect {
private final OxAspectService oxAspectService;
public OxAspect(OxAspectService oxAspectService) {
this.oxAspectService=oxAspectService;
}
#Pointcut("execution(#java.lang.Deprecated * com.oxane.xenon..*(..))"
+ " || execution(* com.oxane.xenon..*.*(..)) && #within(java.lang.Deprecated)")
public void deprecated() {
}
#Before("deprecated()")
public void log(final JoinPoint jp) {
oxAspectService.logDeprecatedMethod(jp);
}
}
Edit:
I have done some research on spring io and found that it can't be done using spring aop. I have to use load time weaving or compile time weaving to achieve what i want. For that i have to use pure aspect j implementation. Correct me if i am wrong.
If I were you I will devide #Pointcut to signle condition like below:
#Pointcut("execution(* com.oxane.xenon..*(..))")
public void anyClassInSubpackage() {
}
#Pointcut("#annotation(java.lang.Deprecated)")
public void deprecatedClass() {
}
#Pointcut("execution(* com.oxane.xenon..*new(..))")
public void anyMethodInSubpackege() {
}
#Pointcut("#within(java.lang.Deprecated)")
public void deprecatedMethod() {
}
#Before("(anyClassInSubpackage() && deprecatedClass()) || (anyMethodInSubpackege() && deprecatedMethod())")
public void myAdvice(final JoinPoint jp){
//TODO
}

Working example of a Singleton

In C#, I want to implement Singletons to provide data in one thread to many other threads.
I have decided to use this lazy form of Singleton from Jon Skeet (thanks, Jon!):
public sealed class Singleton
{
Singleton()
{
}
public static Singleton Instance
{
get
{
return Nested.instance;
}
}
class Nested
{
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Nested()
{
}
internal static readonly Singleton instance = new Singleton();
}
}
So far, so good. ... but how does one use that?
What I want to do is share a single instance of the following data:
public bool myboolean = false ;
public double mydoubles[] = new double[128,3] ;
public IntPtr myhandles[] = new IntPtr[128] ;
How do I declare and reference these data as Singletons?
I also need them to be referenceable across different namespaces.
Many thanks!
// thread-safety
public sealed class Singleton
{
private static Singleton instance = null;
private static readonly object padlock = new object();
private bool myboolean = false;
private double[,] mydoubles = new double[128, 3];
private IntPtr[] myhandles = new IntPtr[128];
Singleton()
{
}
public static Singleton Instance
{
get
{
lock (padlock)
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
}
and to access
//Singleton.Instance.myboolean
//Singleton.Instance.mydoubles
//Singleton.Instance.myhandles

proguard copying methods in interface

after decompiling my interface i found out that proguard duplicated my implemented method in the upper level interface that is somehow a class on its own right.
here's how my interface looks like after obfuscation (note that proguard even added the annotation from the implementation)
package com.company.project.f.a.a;
import java.util.List;
import org.apache.log4j.Logger;
#Component(value="ServiceImpl")
public class a
{
public b a(int i)
{
if((i = b.a(i)) != null)
{
if(i.size() == 0)
{
a_.fatal("It is expected at least one record.");
return null;
} else
{
return (b)i.get(0);
}
} else
{
return null;
}
}
public a()
{
a_ = Logger.getLogger(getClass());
}
public com.company.project.b.a.a a()
{
return b;
}
public void a(com.company.project.b.a.a a1)
{
b = a1;
}
private com.company.project.b.a.a b;
Logger a_;
}
same issue happened with the class below (proguard transforming the interface into a class with the same component name)
#Component("testDao")
public class TestDaoImpl implements TestDao {
#Override
public void testing() {
// TODO Auto-generated method stub
}
solved it :
according to mr eric lafortune , the optimizer is merging interface and class .
so i used
-dontoptimize

Problem getting same class instance passed from one activity to another

I am trying to pass SampleParcelable class object say sampleObj from my ClassA (current) activity to ClassB (a new one), but when i log the objects value, the object's value which i am creating in ClassA is totally different from what i get in ClassB.
ClassA :-
public class ClassA extends Activity
{
private SampleParcelable sampleObj;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
sampleObj = new SampleParcelable();
Log.d("Actual Reference Value", "\t" + sampleObj);
Intent terminateActivity = new Intent( ClassA.this, ClassB.class );
terminateActivity.putExtra("SampleValue", sampleObj);
SampleParcelable readbackCi = terminateActivity.getParcelableExtra("SampleValue");
Log.d("Retrieved Value", "\n\n\t" + readbackCi);
}
}
ClassB :-
public class ClassB extends Activity
{
private SampleParcelable newSampleObj;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
try {
Intent intentObj = getIntent();
Log.d("Intent Value", "intent: " + intentObj.toString());
Log.d("Extra Values", "extras: " + intentObj.getExtras());
newSampleObj = (SampleParcelable) intentObj.getParcelableExtra("SampleValue");
Log.d("New Value", " " + newSampleObj.toString());
} catch (Exception e) {
Log.d("Exception in main", e.toString());
}
}
}
SampleParcelable :-
public class SampleParcelable implements Parcelable
{
public SampleParcelable(Parcel in) {
in.readParcelable(SampleParcelable.class.getClassLoader());
}
public SampleParcelable() {
}
#Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
// TODO Auto-generated method stub
}
public static final Parcelable.Creator<SampleParcelable> CREATOR = new Parcelable.Creator<SampleParcelable>() {
public SampleParcelable createFromParcel(Parcel in) {
return new SampleParcelable(in);
}
public SampleParcelable[] newArray(int size) {
return new SampleParcelable[size];
}
};
}
After debugging I guess, I know 1 reason why my object values are different, because when retrieving object in ClassB using getParcelableExtra() at that time my SampleParcelable class createFromParcel method is called which internally creates a new object. May be i m wrong.
I am not getting any solution for this, i just want same object in my new class so that i can access some values using that object which were set in my ClassA activity.
Thanks in advance
Here how you can achieve what you intend for::
package com.unundoinc.FaceBook.Activity;
import android.os.Parcel;
import android.os.Parcelable;
public class CheckParcelable implements Parcelable
{
private Facebook facebook;
public CheckParcelable() { ; }
/**
*
* Constructor to use when re-constructing object
* from a parcel
*
* #param in a parcel from which to read this object
*/
public CheckParcelable(Parcel in) {
readFromParcel(in);
}
#Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags)
{
// TODO Auto-generated method stub
dest.writeValue(getFacebook());
}
private void readFromParcel(Parcel in) {
// readParcelable needs the ClassLoader
// but that can be picked up from the class
// This will solve the BadParcelableException
// because of ClassNotFoundException
facebook = (Facebook) in.readValue(Facebook.class.getClassLoader());
}
public void setFacebook(Facebook facebook) {
this.facebook = facebook;
}
public Facebook getFacebook() {
return facebook;
}
public static final Parcelable.Creator<CheckParcelable> CREATOR =
new Parcelable.Creator<CheckParcelable>()
{
public CheckParcelable createFromParcel(Parcel in)
{
return new CheckParcelable(in);
}
public CheckParcelable[] newArray(int size) {
return new CheckParcelable[size];
}
};
}
For Using the Parceable You Need to do something like this in the class from where you require pass the object to the other Activity::
Facebook facebook = new Facebook();
facebook.setAccessToken("TIMEPASS");
CheckParcelable parcelable = new CheckParcelable();
parcelable.setFacebook(facebook);
Intent newIntent = new Intent(ActivityA.this, ActivityB.class);
newIntent.putExtra("CheckParcelable", parcelable);
And for getting the Object from Other Activity you require to perform this thing ::
CheckParcelable parcelable = getIntent().getExtras().getParcelable("CheckParcelable");
Facebook facebook = parcelable.getFacebook();
Log.v(TAG, "PARCELABLE IS ::" +facebook.getAccessToken());
I hope this would solve you problem ;D

Problem with design in OOP (Virtual member call in constructor)

I am trying to achieve something like the following:
class Foo
{
public virtual int Number { get; set; }
public Foo(int n)
{
Number = n; //Virtual member call in constructor
}
public void Do() {
Console.WriteLine(Number);
}
}
class Bar : Foo
{
public override int Number
{
get
{
return x.Val;
}
set
{
x.Val = value;
}
}
Bar(int n) : base(n)
{
X x = new X();
x.Val = n;
}
public void F() {
x.Something(); //changes x.Val
}
}
The reason I am doing this is because I need to propagate the call to Do when called from a variable of type Bar.
Now, I can have objects that either inherit from Foo or Bar, thus Number needs to be the way it is now, ie directly expose the Val property of x. This is because I need to allow for the following code:
Bar b = new Bar(5);
b.F(); //changes the value of Val in x
b.Do(); //Needs to print the correct, modified value
The problem here is obviously in Foo, when assigning n to Number (Virtual member call in constructor) since x from the subclass would not have been initialized yet.
What do you think is a better way to structure such a design?
I can't use this current code because I am calling a virtual member from the constructor, which causes the Object Reference not set to an Instance of an Object exception since x in Number from Bar would not have been yet initialized.
My favorite quote:
Favor composition over inheritance
I would separate underlying data from operations:
interface IMyNumber
{
int Number { get; set; }
void Something();
}
class MyNumber : IMyNumber
{
public int Number { get; set; }
public MyNumber(int n)
{
Number = n;
}
void Something() {... }
}
class MyBoxedNumber : IMyNumber
{
int Number { get { ... } set {... } }
void Something() {... }
}
class Bar
{
private IMyNumber_foo;
Bar(IMyNumber foo)
{
_foo = foo;
}
public void F() {
_foo.Something(); //changes x.Val
}
public void Do() {
Console.WriteLine(...)
}
}