I'm extremely new to Java and have been trying to use Nested class for the first time.
I have an outer class with 2 inner class and i'm trying to be able to have
the innerclass
class OuterClass {
...
class Person {
class Like {
}
**public static Map<Integer, Like> Likes;**
}
}
Is it possible in Java ?
In Golang that would look like this for example :
type Like struct {
}
type Person struct {
Name string
**Likes map[int]Like**
}
I might be going the wrong way and maybe a better OOP approch of doing that exist or is it possible this way ?
Yes this is possible and your code will be like
class Client{
class Outer{
class Phone{
class Like{
public void sayHello(){
System.out.println("Hello");
}
}
public static void method(Outer.Phone.Like g){
l.sayHello();
}
}
}
public static void main(String[] args){
Client q = new Client();
Client.Outer o = q.new Outer();
Client.Outer.Phone p = o.new Phone();
Client.Outer.Phone.Like l = p.new Like();
p.method(l); //call sayHello and print Hello
}
Related
I'm trying to create some system with inner class. My code can be summarized to something like this.
public abstract class A {
public abstract void doSomething();
}
public class B {
public final ArrayList<A> list=new ArrayList<A>();
public B(){
}
}
public class C {
private int i;
public C(B b){
b.list.add(new A(){
public void doSomething(){
i++;
}
});
b.list.add(new A(){
public void doSomething(){
System.out.println(i);
}
});
}
}
public static void main (String[] arg) {
B manager=new B();
new C(manager);
new C(manager);
new C(manager);
}
A is abstract class that will be inherited as inner class (in my original code it is listener class), B is some kind of manager class that hold list of As, and C hold data it's data should be only modified or read by it's inner class and upon initialization it add A to the class B. Code itself works fine. But problem is as there will be various kinds of C something like C2, C3 that does different thing and this leads to my code overwhelmed with thousands of unassigned object new C(manager); this make debugging extra hard and code looks really ugly. So it seems to me my approach in the first place was wrong but have no idea how to avoid this. So how should I change my approach to not have thousands of unassigned objects?
My suggestion is: try not to use constructors to do operations that depend on state (i). Use static functions, and save the state in a separate class (we call it a “context”).
import java.util.ArrayList;
public class Demo {
// A
abstract static class InnerListener {
public abstract void onEvent();
}
// B
static class ListenerManager {
public final ArrayList<InnerListener> listeners = new ArrayList<InnerListener>();
}
static class SideEffectContext {
public int i = 0;
}
// C
static class ListenerUtil {
public static void setupListeners(ListenerManager manager, SideEffectContext context) {
manager.listeners.add(new InnerListener() {
public void onEvent() {
context.i++;
}
});
manager.listeners.add(new InnerListener() {
public void onEvent() {
System.out.println(context.i);
}
});
}
}
public static void main(String[] arg) {
var manager = new ListenerManager();
var ctxA = new SideEffectContext();
var ctxShared = new SideEffectContext();
ListenerUtil.setupListeners(manager, ctxA);
ListenerUtil.setupListeners(manager, ctxShared);
ListenerUtil.setupListeners(manager, ctxShared);
}
}
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...
I have created a public class helloworld and I am trying to create an object for class Abc. I have used "new" keyword to create an instance for Abc class.But still I am getting an error "non-static variable this cannot be referenced from a static context." in 4th line.
How do I solve this problem?
public class helloworld {
public static void main (String[] args)
{
Abc obj = new Abc();
}
class Abc
{
int i;
}
}
For simplicity, put class Abc in a different file and make it a public class.
helloworld.java
public class helloworld {
public static void main (String[] args)
{
Abc obj = new Abc();
}
}
Abc.java
public class Abc
{
int i;
}
Or you can declare your class Abc as static:
public class helloworld {
public static void main (String[] args)
{
Abc obj = new Abc();
}
static class Abc
{
int i;
}
}
When you create an inner class, it follows the same rule as members of a class: Static members of a class cannot directly access Instance members. Thus, you will need to declare Abc as a static class.
PS: please use CamelCasing conventions to name your classes. Ex: Use HelloWorld instead of helloworld.
Hope this helps!
First of all: Heed Jon's advise. That said, you can quickly solve this particular problem by changing your inner class into a static class:
static class Abc {
int i;
}
I know this might seem a bit weird, but you cannot refer to regular inner classes without first creating an instance of the outer class. Since the main method is static there is no instance of HelloWorld yet. This means it cannot refer to a regular (instance-bound) inner class only to a static inner class.
Arguably a better solution is to create an instance of your class first thing in your main method:
// class names should be camel case with an upper case first letter
public class HelloWorld {
public static void main (String[] args) {
HelloWorld app = new HelloWorld();
app.start();
}
// note that this is not a static method
private void start() {
Abc obj = new Abc();
}
private class Abc {
int i;
}
}
Abc is an inner class of helloworld. To instantiate it you need an instance of helloworld
Abc abc = new helloworld().new Abc();
or make Abc a static inner class.
static class Abc {}
The first awnser is correct but don't be easy. This is the easy way for a eclipse project o similar.
Create a ABC class:
public class Abc
{
int i;
}
Import in a Hello world class and declare static:
import Abc;
public class HelloWorld{
private static Abc abc=new Abc();
public static void main(String[] args){
//do something
}
}
All IDE that you use. Help you to import the class : )
I try to access an inner class method from another inner class. Both inner classes are declared in the same outer class:
class OuterFoo{
class innerFoo1{
public void methodFoo1(){
System.out.println(" Hello, i am in the inner foo 1");
}
}
class innerFoo2{
public void methodFoo2(){
System.out.println(" Hello, i am in the inner foo 2");
}
}
}
Now, I would like to access methodFoo1 from methodFoo2.
Any help will be appreciated.
You need a reference to an instance of the other inner class. Like this:
public class OuterFoo {
private class InnerFoo1 {
private void helloFoo1 () {
System.out.println("foo1");
InnerFoo2 foo2 = new InnerFoo2();
foo2.helloFoo2();
}
}
private class InnerFoo2 {
private void helloFoo2 () {
System.out.println("foo2");
InnerFoo1 foo1 = new InnerFoo1();
foo1.helloFoo1();
}
}
}
Depending on what you want your real program should do (if you don't need to instantiate the class InnerFoo and only need a call to a static method), you may also make the class innerFoo2 and the method methodFoo2 static.
public class OuterFoo{
class innerFoo1{
public void methodFoo1(){
System.out.println(" Hello, i am in the inner foo 1");
OuterFoo.innerFoo2.methodFoo2();
}
}
static class innerFoo2{
public static void methodFoo2(){
System.out.println(" Hello, i am in the inner foo 2");
}
}
}
If your inner classes are instanciated into the OuterFoo
You can do it this way :
class OuterFoo{
final innerFoo1 if1 = new innerFoo1();
final innerFoo1 if2 = new innerFoo2();
class innerFoo1{
public void methodFoo1(){
System.out.println(" Hello, i am in the inner foo 1");
if2.methodFoo2();
}
}
class innerFoo2{
public void methodFoo2(){
System.out.println(" Hello, i am in the inner foo 2");
if1.methodFoo1();
}
}
}
Try this code
public class OuterFoo{
class innerFoo1{
public void methodFoo1(){
System.out.println(" Hello, i am in the inner foo 1");
}
}
class innerFoo2{
public void methodFoo2(){
System.out.println(" Hello, i am in the inner foo 2");
}
}
void displayInnerFoo1(){
innerFoo1 object1= new innerFoo1();
object1.methodFoo1();
}
void displayInnerFoo2(){
innerFoo2 object2= new innerFoo2();
object2.methodFoo2();
}
public static void main(String args[]){
OuterFoo objectParent= new OuterFoo();
objectParent.displayInnerFoo1();
objectParent.displayInnerFoo2();
}
}
Create the Object of inner class then simply use the dot operator to access it.
ClassName obj = new ClassName();
obj.MethodName();
How to access the public function of private static inner class in some other class Suppose there is a class structure like below :-
public class Outer{
private static Inner {
public void func() {
}
}
}
And there is another class :-
class UseFunc {
// I have to use the func() here
}
If I use like this it will give error : - create object of Inner like Outer.Inner oi = new Outer.Inner();
access oi.func() //as Inner is private class
Okay, this is a very bad (I mean, really terrible) implementation but it works:
public class Outer
{
private static class Inner
{
public void func()
{
}
}
public void encapsulatedFunc()
{
new Inner().func();
}
}
class UseFunc
{
public static void main(String[] args)
{
new Outer().encapsulatedFunc();
}
}
I can only imagine that code being used for educational purpose as a "What not to do" example.