Java: reusable encapsulation with interface, abstract class or inner classes? - java

I try to encapsulate. Exeption from interface, static inner class working, non-static inner class not working, cannot understand terminology: nested classes, inner classes, nested interfaces, interface-abstract-class -- sounds too Repetitive!
BAD! --- Exception 'illegal type' from interface apparently because values being constants(?!)
static interface userInfo
{
File startingFile=new File(".");
String startingPath="dummy";
try{
startingPath=startingFile.getCanonicalPath();
}catch(Exception e){e.printStackTrace();}
}
MANY WAYS TO DO IT: Interface, static inner class image VS non-static innner class image
import java.io.*;
import java.util.*;
public class listTest{
public interface hello{String word="hello word from Interface!";}
public static class staticTest{
staticTest(){}
private String hejo="hello hallo from Static class with image";
public void printHallooo(){System.out.println(hejo);}
}
public class nonStatic{
nonStatic(){}
public void printNonStatic(){System.out.println("Inside non-static class with an image!");}
}
public static class staticMethodtest{
private static String test="if you see mee, you printed static-class-static-field!";
}
public static void main(String[] args){
//INTERFACE TEST
System.out.println(hello.word);
//INNNER CLASS STATIC TEST
staticTest h=new staticTest();
h.printHallooo();
//INNER CLASS NON-STATIC TEST
nonStatic ns=(new listTest()).new nonStatic();
ns.printNonStatic();
//INNER CLASS STATIC-CLASS STATIC FIELD TEST
System.out.println(staticMethodtest.test);
}
}
OUTPUT
hello word from Interface!
hello hallo from Static class with image
Inside non-static class with an image!
if you see mee, you printed static-class-static-field!
Related
Nesting classes
inner classes?
interfacses

The problem is that you're writing code outside of a method. You do need a class for this and you must put your code inside a method. For example:
static class UserInfo
{
public static void myMethod()
{
File startingFile = new File(".");
String startingPath = "dummy";
try
{
startingPath = startingFile.getCanonicalPath();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
This does assume that java.io.File was imported.
You can then call UserInfo.myMethod();
You might also want to import java.util.IOException and catch an IOException instead of a general Exception.
Also, classes and interfaces start with a capital letter by Java conventions.
EDIT: To describe your recent comment on your question:
Use an interface when you want to force similar classes (Think different types of DVD players) to have the same basic functionality (playing dvds, stopping, pausing. You use an abstract class similarly, but when all of the classes will implement some of the same things the same way.

I think you wanted to do this:
static class userInfo
{
public static void something() {
File startingFile=new File(".");
String startingPath="dummy";
try{
startingPath=startingFile.getCanonicalPath();
}catch(Exception e){e.printStackTrace();}
}
}

you cant put code in an interface, an interface only describes how an object will behave. Even when you use Classes, you should put this kind of code in a method, and not directly in the class body.

You can't have actual code in an interface, only method signatures and constants. What are you trying to do?

Looks like you want to write a class here.

You cannot have code in interfaces. Just method signatures.
Top level interfaces cannot be static.
I suggest you start your learning of Java here.

Related

Create a Class whose object can not be created

I am studying for my BS, and my professor has given me a task, he said: Create a class without using any access modifier or interface keyword whose object can't be created.
I went through Google but can't find the solution. How can this be done in Java?
Enums are classes (JLS§8.9) that cannot be instantiated and cannot be subclassed; just create one without any values:
enum Foo {}
Other possibilities depending on interpretation:
JonK and T.J. Crowder considered throwing an exception from the constructor:
final class Example {
Example() {
throw new Exception();
}
}
But nick zoum pointed out that an instance is still created and exists, briefly, prior to the exception, even though it cannot (in the example above) be retained.
nick zoum considered abstract:
abstract class Example {
}
...but T.J. Crowder pointed out that abstract classes can be subclassed (they cannot be final), and a subclass instance "is a" superclass instance.
I'm not a Java person, but other answers gave me this idea:
import java.util.*;
import java.lang.*;
import java.io.*;
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
Object o = new Problematic();
// unreachable
}
}
class Problematic
{
static
{
int i = 1 / 0 ;
}
}
Try it on ideone
I'm pretty sure there's no way of making a Problematic and surviving...
(Note that when I tried throw new Exception(); in the static initializer it wouldn't compile)
Have you tried the keyword abstract?
For example:
abstract class Test{}
Of course this can be overwritten, so please check this answer for a more foolproof design.
Without hearing exactly how your professor phrased it, "without using any access-modifier" might mean they are attempting to teach you how the "default" access modifier works?
In which case:
package mypackage.nocreate;
class MyClass {
}
And then:
package mypackage;
import mypackage.nocreate.MyClass;
public class Test {
public static void main(String[] args) {
new MyClass(); // not allowed - in a different package
}
}
You could argue that - in the source code at least - that doesn't use any access modifier :)
Anonymous inner class should be the answer.
Example:
public abstract class HelloWorld{
abstract void x();
public static void main(String []args){
System.out.println("Hello World");
HelloWorld h = new HelloWorld(){
void x(){
System.out.println(" ");
}
};
h.x();
}
}
A class is created, but it's name is decided by the compiler which extends the HelloWorld class and provides the implementation of the x() method.

meaning of protected static A.B newvar = null

I was going throught a huge java project and I came across this line in a file.I am new to java and don't know what this means.Or more specifically
Should I look at PSStreamer.java OR Client.java to see the methods and member variables of the below object.
protected static PSStreamer.Client packetClient = null;
This is what's being declared:
protected // protected visibility modifier
static // a class (static) member
PSStreamer.Client // Client is an inner class of PSStreamer
packetClient = null; // variable name, null initial value
You should look inside PSStreamer to find the inner class Client, and that's where you'll find the attributes and methods of packetClient.
That is a static inner class.
It would look like this: (in PSStreamer.java):
class PSStreamer {
...
static class Client {
...
}
}
That is a static nested class. It should be defined in the source code as
public class PSStreamer {
public static class Client {
// ..
}
// ..
}
So, you should be looking inside PSStreamer.java. Read more about Nested Classes.
Nested classes that are declared static are simply called static nested classes. Non-static nested classes are called inner classes.
Also, take a look at this SO link: Java inner class and static nested class

Java function (method) available everywhere (global)

I've recently (4 days ago) started programming in JAVA. I have some overall programming experience from C++ and PHP. My question is: can we implement a function in JAVA, that is available in all classes? I'm thinking of some global logging function, that I need to call in several places (log events, errors, etc.).
Imagine I have two classes, A and B. I need to call logging function in both of them, but I don't want to copy whole function body (awful thing I believe), and I want to call it strict (without creating another class, instantiating it, and then calling from the instance), like logEvent(someVariable). So I should use an abstract class C, which A and B will extend, BUT they are already an extension of other class (built-in). Since multiple inheritance isn't allowed (is it?), I need to do some trick. Singleton is not pleasing me too. In PHP or C++ I would just create separate file with function body and then include it.
Here is how I want to use it:
public class A extends SomeClass {
String error = "Error from class A";
logEvent(error);
}
public class B extends SomeOtherClass {
String error = "Error from class B";
logEvent(error);
}
Put a static method in any class (it could be a utils class, or whatever), then call it like this: ClassName.functionName()
Static methods belong to the class, not instances of the class, so you don't need to instantiate the class to access the method
But everything in Java has to be in a class, so you can't access it without the class name.
You should use static method:
package xxx;
public class Util{
public static void logEvent(String error){
...
}
}
and import static:
import static xxx.Util.*;
public class A extends SomeClass {
String error = "Error from class A";
logEvent(error);
}
You may use static method.
Define a class with a static method:
public class Util{
public static void logEvent(String error){
...
}
}
Then, you can use static metod like this way:
public class A extends SomeClass {
String error = "Error from class A";
Util.logEvent(error);
}
you may take a look here to learn more about static method, http://www.leepoint.net/notes-java/flow/methods/50static-methods.html

Calling a static method of an abstract class in another class

I have a class Employee
import javax.swing.*;
public abstract class Employee {
public static void searchEmp(int id) {
JOptionPane.showMessageDialog(null, "done");
}
}
Now I have another class test:
public class `test` {
public static void main(String args[]) {
searchEmp(2);// here my programme give error
}
}
I want to call the searchEmp() which is part of Employee from a class test but it gives an error. Please suggest any solution without inheritance.
You have to call Employee.searchEmp().
The static method searchEmp() is still a member of the class Employee and you must make a static call via its class.
Also the class Employee must be visible to the class test, otherwise you have to import it. I assume the two classes reside in the same package so this will not be a problem in your case.
Static methods and properties are bound to class. So you need to use ClassName.methodName or ClassName.propertyName.
Employee.searchEmp();
Your Test class doesnt have a static searchEmp(int) method, thus the error:
searchEmp(2);// here my programme give error
should be
Employee.searchEmp(2);
static methods are called using ClassName.staticMethod()

jMockit's access to a private class

I have a public class with a private class inside it:
public class Out
{
private class In
{
public String afterLogic;
public In(String parameter)
{
this.afterLogic = parameter+"!";
}
}
}
And wanted to test the In class with jMockit. Something along these lines:
#Test
public void OutInTest()
{
Out outer = new Out();
Object ob = Deencapsulation.newInnerInstance("In", outer); //LINE X
}
The problema is, in LINE X, when trying to cast ob to In, the In class is not recognized.
Any idea how to solve this?
Thanks!
The only constructor in class In takes a String argument. Therefore, you need to pass the argument value:
Object ob = Deencapsulation.newInnerInstance("In", outer, "test");
As suggested in the comment one way is to change the access modifier of the inner class from private to public.
Second way (in case you don't want to make your inner class public), you can test the public method of outer class which is actually calling the inner class methods.
Change the scope of the inner class to default then make sure that the test is in the same package.
There are two approaches, first as mentioned in other posts to change the scope to public. The second which I support is, to avoid testing private class altogether. Since the tests should be written against testable code or methods of the class and not against default behavior.

Categories