The isAbsolute method does not have a body in the path interface, but I can run it in the following code. How is this possible?
Path path= Paths.get("D:\\Example\\1.txt");
System.out.println(path.isAbsolute());//prints true
Imagine following code:
public interface Foo {
public boolean bar();
}
public class Fooz implements Foo {
#Override
public boolean bar() {
return false;
}
}
And:
public Foo getFoo() {
return new Fooz();
}
public static void main(String[] args) {
Foo myFoo = getFoo();
System.out.println(myFoo.bar()) //false
}
If you are looking for actual implementation of this function, I advise looking thru the source code of JVM of your choosing. Example of one such implementation can be found in UnixPath.java on OpenJDK github repo.
Related
Hello I am new to java and I wanted to make a variable that would be an object of different classes based on a string condition. I am not sure how to do that.
Here is what I am trying to explain
public class Foo {
Object obj; // I want this variable to be dynamic based on the condition in the constructor
public Foo(String str){ // Constructor
if(str.equals("bar")){
this.obj = new Bar();
}
else{
this.obj = new Baz();
}
}
I want it this way because I will be using this obj variable later on to call methods in either Bar or Baz which both implement the methods of same name, but different code.
Please check this java code, You will understand how to use interfaces to resolve this problem
package com.company;
public class Main {
public static void main(String[] args) {
Foo foo = new Foo("bar");
foo.obj.hello();
}
}
class Foo {
Ba obj;
Foo(String str) { // Constructor
if (str.equals("bar")) {
this.obj = new Bar();
} else {
this.obj = new Baz();
}
}
}
interface Ba {
void hello();
}
class Bar implements Ba {
public void hello(){
System.out.println(" Hello Bar");
}
}
class Baz implements Ba {
public void hello(){
System.out.println(" Hello Baz");
}
}
Sounds like the strategy pattern, here's a crude implememntation:
public class Foo {
Map<String, Common> strategyPattern = new HashMap<>();
private Common obj;
{
// set this up how you want, this is a static code block common to all classes
// if you're using spring you can autowire these
// Bar and Baz both implement Common interface
strategyPattern.put("bar", new Bar());
strategyPattern.put("bar", new Baz());
}
public Foo(String str) { // Constructor
this.obj = strategyPattern.get(str);
}
}
Best way is to create interface instead of object.
assume TestInterface is an interface having same methods which are in Bar and Buz.
interface TestInterface {
testMethod1();
testMethod2();
}
class Bar implements TestInterface{
testMethod1(){
// Your code
}
testMethod1(){
// Your code
}
}
class Baz implements TestInterface{
testMethod1(){
// Your code
}
testMethod2(){
// Your code
}
}
public class Foo {
TestInterface obj; // Here change object to interface
public Foo(String str){ // Constructor
if(str.equals("bar")){
this.obj = new Bar();
}
else{
this.obj = new Baz();
}
}
Foo foo = new Foo("Bar");
I have written below code, just to play with interface, Would you
please tell where I have gone wrong here?
This is my interface:
package com.home.intetest;
public interface IFoo {
public abstract String doWork(String str) throws Exception;
}
This is where I have implemented,
package com.home.intetest;
public class FooImpl implements IFoo {
#Override
public String doWork(String str) throws Exception {
if(str !=null) {
System.out.println(str);
}else{
System.out.println("Wrongggg");
}
return str;
}
}
Now I am trying to call them from main, using getter method, its giving me error,in line where I am using getiFoo method
package com.home.intetest;
public class TestMain {
private IFoo iFoo;
public IFoo getiFoo() {
return iFoo;
}
public void setiFoo(IFoo iFoo) {
this.iFoo = iFoo;
}
public static void main(String[] args) {
String str = "Work method";
callWorkMethod(str);
}
private static void callWorkMethod(String str) {
String s = getiFoo().doWork(str);
}
}
1
The line
getiFoo().doWork(str);
can not be called, you need a instance of TestMail first! So boot-up your Application like this:
new TestMain().getiFoo().doWork(str);
2
The error you recieve is a NullPointerException now because iFoo is always null.
Create a instance in the getter using the default constructor like this:
public IFoo getiFoo() {
if (iFoo == null) {
iFoo = new FooImpl();
}
return iFoo;
}
Or inside the declaration like this:
private IFoo iFoo = new FooImpl();
I want to change the object return from call to a constuctor
FROM
public class A {
public A(){
}
public String sayHello() {
return "hello";
}
public String foo() {
return "foo";
}
}
TO
public class AWrapped extends A {
private A wrapped;
public AWrapped() {
super();
}
public AWrapped(A pWrapped) {
wrapped=pWrapped;
}
public String foo() {
return wrapped.foo();
}
public String sayHello {
return "gday mate";
}
}
What i want to do is to change the object that is returned from a call
A a = new A();
a.sayHello() returns "gday mate"
a is an instaceof AWrapped
I understand that this would usually be done with a factory pattern but I dont have access to the code of A or the code that makes new A's. And there are 1000s of places that A can be created.
It seems that Aspectj might do the trick, but i dont know much about it, If AspectJ would do the trick how to I get around the infinite wrapping i need to know that its being consturcted from within and aspect so it doesnt wrapp it again.
Thanks for the help
Jon
If I understand you right you could do the following:
I've created three packages:
aspectj for the aspect and AWrapped.java
unknown for A.java (could also be Bytecode but then you have to use Load Time Weaving)
main to test A a = new A();
MyAspect to return the AWrapped object if a new() call is made on class A:
package aspectj;
import unknown.A;
#Aspect
public class MyAspect {
#Pointcut("call(unknown.A.new(..)) && !within(aspectj..*)")
public static void init(ProceedingJoinPoint pjp) {
}
#Around("init(pjp)")
public Object initAdvice(ProceedingJoinPoint pjp) throws Throwable{
Object ret = pjp.proceed();
return new AWrapped((A) ret);
}
}
For testing:
package main;
import unknown.A;
public class Main {
public static void main(String[] args) {
A a = new A();
System.out.println(a.sayHello());
}
}
This outputs:
gday mate
I am a Java beginner.
Can anyone explain why is it printing output 2?
interface Foo {
int bar();
}
public class Beta {
class A implements Foo {
public int bar() {
return 1;
}
}
public int fubar(final Foo foo) {
return foo.bar();
}
public void testFoo()// 2
{
class A implements Foo {
public int bar() {
return 2;
}
}
System.out.println(fubar(new A()));
}
public static void main(String[] args) {
new Beta().testFoo();
}
}
That is because you redefined Class A here:
class A implements Foo {
public int bar() {
return 2;
}
}
System.out.println(fubar(new A()));
So when you do return foo.bar(); you return 2
Because the innermost definition of A is in the testFoo() method, and its method bar() return 2.
You may also find the answer to my question from today interesting.
When you say, System.out.println(fubar(new A()));
the class A created is the one defined inside testFoo().
There are many places in java where you can hide a broader name with a more local name. This is true of parameters vs member variables, class names etc. In your case, you are hiding Beta.A with the A you defined in the method.
I'm using the Apache Commons EqualsBuilder to build the equals method for a non-static Java inner class. For example:
import org.apache.commons.lang.builder.EqualsBuilder;
public class Foo {
public class Bar {
private Bar() {}
public Foo getMyFoo() {
return Foo.this
}
private int myInt = 0;
public boolean equals(Object o) {
if (o == null || o.getClass() != getClass) return false;
Bar other = (Bar) o;
return new EqualsBuilder()
.append(getMyFoo(), other.getMyFoo())
.append(myInt, other.myInt)
.isEquals();
}
}
public Bar createBar(...) {
//sensible implementation
}
public Bar createOtherBar(...) {
//another implementation
}
public boolean equals(Object o) {
//sensible equals implementation
}
}
Is there syntax by which I can refer to other's Foo reference apart from declaring the getMyFoo() method? Something like other.Foo.this (which doesn't work)?
No.
The best way is probably what you suggested: add a getFoo() method to your inner class.
No, not possible without a getter. The 'this' keyword will always point to the current instance. I'm quite curious why you would want to do this... seems like you are doing composition in the wrong way.
public class Foo {
public Bar createBar(){
Bar bar = new Bar(this)
return bar;
}
}
public class Bar {
Foo foo;
public Bar(Foo foo){
this.foo = foo;
}
public boolean equals(Object other) {
return foo.equals(other.foo);
}
}
Since using Foo.this limits creation of the inner class (Foo myFoo = new Foo(); myFoo.new Bar(); to an instance I'd say this is much cleaner.
yes:
public class Foo {
public class Bar {
public Foo getMyFoo() {
return Foo.this;
}
}
public Foo foo(Bar bar) {
return bar.getMyFoo();
}
public static void main(String[] arguments) {
Foo foo1=new Foo();
Bar bar1=foo1.new Bar();
Foo foo=(new Foo()).foo(bar1);
System.out.println(foo==foo1);
}
}