I've following class
class MyClass implements Intrfc {
String pickmeUp = "Its Me";
public static void main(String[] args){
Intrfc ob = new MyClass();
ob.pickmeUp; ---> How can I access this way ?
}
}
Is there any way to access class variable using Interface type ?
Is there any way to access class variable using Interface type ?
No. That is the whole point of an interface.
And yes, interfaces only give you behavior (methods), not "state" (variables/fields). That is how things are in Java.
Of course, you can always use instanceof to check if the actual object is of some more specific type, to then cast to that type. But as said, that defeats the purpose of using interfaces!
No, you can't access the class variable using interface type, but the interface can define method that can access to the variable.
interface Intrfc {
public String getPickmeUp();
}
class MyClass implements Intrfc {
String pickmeUp = "Its Me";
public String getPickmeUp(){
return pickmeUp;
}
public static void main(String[] args){
Intrfc ob = new MyClass();
ob.getPickmeUp();
}
}
In this definition:
class MyClass implements Intrfc {
String pickmeUp = "Its Me";
}
the field pickmeUp is not even a member of Intrfc interface, so there is no possibility to reach for it using just the interface. pickmeUp is a member of a concrete class - MyClass.
If you want to use the method of a class using the object of an interface you can do it as follows:
//Interface:
public interface TestOne {
int a = 5;
void test();
static void testOne(){
System.out.println("Great!!!");
}
default void testTwo(){
System.out.println("Wow!!!");
}
}
//-------------------
//Class implementing it:
package SP;
public class TestInterfacesImp implements Test1, TestOne{
#Override
public void test() {
System.out.println("I Love java");
}
public void testM() {
System.out.println("I Love java too");
}
public static void main(String[] args) {
TestOne.testOne();
TestOne obj = new TestInterfacesImp();
obj.testTwo();
TestInterfacesImp objImp = new TestInterfacesImp();
objImp.test();
((TestInterfacesImp) obj).testM(); //Here casting is done we have casted to class type
}
}
Hope this helps...
Related
I want to access an object i created in a new class but it returns that the object " cannot be resolved".
thanks for anyone who helps:)
here is my code :
public class lion {
int weight;
int height;
String color;
double roardecibles;
public void lioncolor() {
System.out.println(color);
}
}
public class blacklion {
lion blackLion;{
blackLion = new lion();
blackLion.weight =4;
blackLion.height =3;
blackLion.color = "black";
blackLion.roardecibles = 5.5;
}
}
public class zoo {
public static void main(String[] args) {
blackLion.lioncolor(); //here it dosent work//
}
}
There's a difference between an object and a class. Think of a class as a blueprint, that's what you did when you defined it in public class blacklion. But you didn't actually build something with the blueprint. To create an object you have to instantiate it, using the new keyword.
public static void main(String[] args) {
blacklion lion = new blacklion();
lion.lioncolor(); //here it dosent work//
}
Usually, you want to instantiate an Object of your class that you can then access from where u created it. If you want to access methods or variables of a class directly you want to declare those as public and static.
Hey looks like you should check out this resource:
https://docs.oracle.com/javase/tutorial/
Specifically the section of how classes work:
https://docs.oracle.com/javase/tutorial/java/concepts/class.html
this code
public static void main(String[] args)
{
blackLion.lioncolor(); //here it dosent work//
}
needs an instance of the object in order to call the lioncolor() method
when you extend a private class. Are the public and protected members of class become private. if not any explanation.
if you extend a nested private class, it wont change public/protected modifiers of the members. Here is an example :
public class Clazz {
private static class NestedClazz {
public int value = 123;
}
public static class NestedClazzExt extends NestedClazz {
}
}
you can now access the inherited member: value from outside
public static void main(String[] args) {
NestedClazzExt nestedClazz = new Clazz.NestedClazzExt();
System.out.println(nestedClazz.value);
}
you can create private class in side a class . We call it as Nested classe. Means a class inside a class. The Concept itself is saying that you can create private class in side another class. The private class will act like as data member to the outer class.
So, You can't extend the private class.
Based on your query I tried to prepare a simple class.
public class pvtClass {
private class As {
public String abc = "private attribute";
public void print(){
System.out.println("privateClass");
}
}
class Ab extends As{
public String ab = "extended attribute";
public void printAb(){
System.out.println("extended class");
print();
System.out.println(abc);
}
}
public static void main(String as[]){
Ab ab1 = (new pvtClass()).new Ab();
As as1 = (new pvtClass()).new As();
ab1.printAb();
as1.print();
System.out.println(as1.abc);
}
}
If you have a look at this class, I have a private class named "As" which has public attribute and public methods. I have another class named "Ab" which extends "As". I have written a main method to invoke the private attribute and methods.
below is the output for the code snippet:
extended class
privateClass
private attribute
privateClass
private attribute
There is a difference between the access of the members of a class and the access to the type itself.
public class C {
private class InnerP1 {
public void m() {
System.out.println("InnerP1.m()");
}
}
private class InnerP2 extends InnerP1 {
public void p() {
this.m();
System.out.println("InnerP2.p()");
}
}
public InnerP1 strange() {
return new InnerP2();
}
}
In this example, the interface I is visible from outside class C. The classes InnerP1 and InnerP2 are not visible from outside C. Jave itself makes not restrictions to the visibility of types you use in your public interface. The method strange() of class C returns a result of class InnerP1. Since outside of C we do not know anything about the class InnerP1 other than it is subtype of Object, the only thing we can do is use the result of strange() as an Object.
public class D {
public static void main(String[] args) {
C c = new C();
Object o = c.strange();
if(o.equals(c.strange())) {
System.out.println("Strange things are going on here!");
}
}
}
As #KnusperPudding pointed out already, the visiblity of public members is not changed, we might just not have enough knowledge of the type itself to access them.
Access to members cannot be restricted by sub-classing. When you mark a class as private then access via the class name is restricted i.e. to the same .java file, however once you have an instance of this class it can be accessed at least as easily as the super class.
I want to get the implementation class name from my interface object — is there any way to do this?
I know I can use instanceof to check the implementation object, but in my application there are nearly 20 to 30 classes implementing the same interface to override one particular method.
I want to figure out which particular method it is going to call.
Just use object.getClass() - it will return the runtime class used implementing your interface:
public class Test {
public interface MyInterface { }
static class AClass implements MyInterface { }
public static void main(String[] args) {
MyInterface object = new AClass();
System.out.println(object.getClass());
}
}
A simple getClass() on the Object would work.
example :
public class SquaresProblem implements MyInterface {
public static void main(String[] args) {
MyInterface myi = new SquaresProblem();
System.out.println(myi.getClass()); // use getClass().getName() to get just the name
SomeOtherClass.printPassedClassname(myi);
}
#Override
public void someMethod() {
System.out.println("in SquaresProblem");
}
}
interface MyInterface {
public void someMethod();
}
class SomeOtherClass {
public static void printPassedClassname(MyInterface myi) {
System.out.println("SomeOtherClass : ");
System.out.println(myi.getClass()); // use getClass().getName() to get just the name
}
}
O/P :
class SquaresProblem --> class name
SomeOtherClass :
class SquaresProblem --> class name
I have 2 classes the static main class and class B. I'm trying to pass main to B, where there is a method that sets fields.
Can this be done?
If so, could you please provide examples?
public static void main(String[] args) {
ArrayList a = new ArrayList()
class b = new class()
b.update(b);
}
class a {
public void update(ArrayList a) {
//updates the encapsulated arrayList field
}
}
The error message keeps on saying that one is static and the other is non-static, but they should be pointing the same object
I'm not entirely sure what you are trying to do, but here is an example that shows that you can pass an instance of the main class into another class:
public class A {
private String str = null;
public static void main(String[] args) {
A a = new A();
B b = new B(a);
System.out.println(a.getStr());
}
public String getStr() {
return this.str;
}
public void setStr(String str) {
this.str = str;
}
}
public class B {
public B(A a) {
a.setA("hello");
}
}
Running this code will print out hello.
main is static and public, so you can call it from any other class as any other public static method: statically.
if you have a class A that contains a
public static void main(String[] args)
method, then class B can call this method like
A.main(s);
where s is String[]
your question is far from clear, so I suggest you to add more code samples to make it clear what you're really trying to do.
public class Test {
public static void main(String[] args) {
DemoAbstractClass abstractClass = new DemoAbstractClass() {
private String val;
#Override
public void runner() {
val = "test";
System.out.println(val);
this.run();
}
public String getVal() {
return val;
}
};
abstractClass.runner();
/**
* I want to access getVal method here
*/
}
}
abstract class DemoAbstractClass {
public void run() {
System.out.println("running");
}
public abstract void runner();
}
Here, I'm declaring an abstract class DemoAbstractClass. I can obviously create a new class that extends this class and add this method to it. But, I would prefer not doing that in my scenario.
Is there any other way to access getVal method in above code??
You can't. You need to make a proper (non-anomous) class out of it. Make it an inner private class if you want to limit its scope.
Alternatively, you could use a StringBuffer and share a referense to it between the methods. Not extremely clean however.
Related question:
Accessing inner anonymous class members
Short of using reflection, you cannot as you have no access to the concrete type of the object to be able to bind the methodcall to
If you don want to do something like this in a sane manner, declare a named class and use that as the type of abstractClass
Unfortunately, if you cannot name the type, you cannot access the methods at the language level.
What you can do, though, is use the reflection API to get a Method object and invoke it on this object.
This, however, is pretty slow. A private class or private interface would be much faster.
I can obviously create a new class that extends this class and add this method to it.
You've already done this; the end result was an anonymous inner class: new DemoAbstractClass() { ... }; If you just moved that declaration into its own class -- you can even make it a private class -- you can access getVal.
Per your example above:
public class Test {
public static void main(String[] args) {
DemoClass abstractClass = new DemoClass();
abstractClass.runner();
/**
* I want to access getVal method here
*/
abstractClass.getVal(); // can do this here now
}
private class DemoClass extends DemoAbstractClass {
private String val;
#Override
public void runner() {
val = "test";
System.out.println(val);
this.run();
}
public String getVal() {
return val;
}
}
}
}
Another option is to make a StringBuilder a member of the main method and use the closure nature of anonymous inner methods:
public static void main(String[] args) {
final StringBuilder value = new StringBuilder();
DemoAbstractClass abstractClass = new DemoAbstractClass() {
#Override
public void runner() {
value.append( "test" );
System.out.println(val);
this.run();
}
};
abstractClass.runner();
// use val here...
String val = value.toString();
}