In the below code, in class_1 and class_2 both extends from AbstractClass. I am trying when I call:
c1.setValid(5)
The following two lines, returns 5 as well:
System.out.println(c1.getValid());
System.out.println(c2.getValid());
pleas let me know how can I modify the Super class to achieve that.
main:
public class Main {
public static void main (String[] args) {
Class_1 c1 = new Class_1();
Class_2 c2 = new Class_2();
System.out.println(c1.getValid());
System.out.println(c2.getValid());
c1.setValid(5);
System.out.println(c1.getValid());
System.out.println(c2.getValid());
}
}
class_1
public class Class_1 extends AbstractClass {
public Class_1() {
// TODO Auto-generated constructor stub
}
public void setValid(int v) {
SetValid(v);
}
public int getValid() {
return GetValid();
}
}
class_2.:
public class Class_2 extends AbstractClass {
public Class_2() {
// TODO Auto-generated constructor stub
}
public void setValid(int v) {
SetValid(v);
}
public int getValid() {
return GetValid();
}
}
code:
public abstract class AbstractClass {
public int isValid = -1;
public void SetValid(int value) {
this.isValid = value;
}
public int GetValid() {
return this.isValid;
}
You can delete setValid and getValid from Class 1 and 2
and use the parent's function SetValid and GetValid
If that is your question.
If your goal is to have all instances of your class to always have the same value, then you can simply use the static keyword.
public abstract class AbstractClass {
public static int isValid = -1;
...
}
When static is used for a global variable, you're essentially declaring that this global variable will be shared by every instance of this class, including it's children.
Therefore, updating isValid with a new value in Class_1 will cause Class_2 to have the same value that Class_1 updated.
Related
I have some classes nested one in another
public abstract class I
{
public abstract int f();
}
public class J
{
private List<I> li;
public J(List<I> l)
{
li = l;
}
}
public class A // first class
{
private int x; // field of A
public class B extends J // second class
{
public B()
{
super(new ArrayList<I>() // super call
{{ // array initializer
add(new I() // third class
{
#Override
public int f()
{
return x; // <- here!!!
}
});
}});
}
}
}
Under these conditions, I get the error: "error: no enclosing instance of type A is in scope". Removing any element from this setup fixes this error. Also, taking x and saving it to another variable then using that variable also works.
What is happening here? It seems like a bug in a compiler for me.
It is not allowed to have 2 public classes in one Java File and file name should be same as public class name.
To experiment with your code I made a new Test class like this. I see no errors reported (using Java 8). Perhaps this is a build issue.
public class Test {
public abstract class I {
public abstract int f();
}
public class J {
private List<I> li;
public J(List<I> l) {
li = l;
}
}
public class A // first class
{
private int x; // field of A
public class B extends J // second class
{
public B() {
super(new ArrayList<I>() // super call
{
{ // array initializer
add(new I() // third class
{
#Override
public int f() {
return x; // <- here!!!
}
});
}
});
}
}
}
public void test() {
System.out.println("Hello");
}
public static void main(String args[]) {
//<editor-fold defaultstate="collapsed" desc="test">
try {
new Test().test();
} catch (Throwable t) {
t.printStackTrace(System.err);
}
//</editor-fold>
}
}
Java 7 also seems to accept this code.
I have the following need and please help me to write good and abstract class.
Different types of operations is needed based on the type
I have a abstract class,
abstract public class FileHelper{
//Template method
//This method defines a generic structure for parsing data
public void parseDataAndGenerateFile(String fileDownloadType)
{
createHeader(fileDownloadType);
generateFile();
}
//We have to write output in a excel file so this step will be same for all subclasses
public void createHeader(String fileDownloadType)
{
System.out.println('Creating HEADER in EXCEL');
}
public void generateFile(String fileDownloadType)
{
System.out.println('Output generated,writing to XLX');
}
}
public class ExcelDataParser extends FileHelper {
String fileDownloadType="";
}
public class TemplateMethodMain {
public static void main(String[] args) {
String fileDownloadType="expired";
ExcelDataParser csvDataParser=new ExcelDataParser();
csvDataParser.parseDataAndGenerateFile(fileDownloadType);
}
}
Please help me and correct me to have a good way of doing this.
If you want to use an abstract base class, you better should declare an abstract method String getDownloadType() in your abstract base class. These method must be overridden by the derived classes and the type could be fix in the derived class.
For example:
abstract public class FileHelper {
abstract String getFileDownloadType();
public void parseDataAndGenerateFile() {
createHeader();
generateFile();
}
public void createHeader() {
if ("expired".equals(getFileDownloadType())) {
} else {
}
}
public void generateFile() {
if ("expired".equals(getFileDownloadType())) {
} else {
}
}
}
public class ExcelDataParser extends FileHelper {
#Override
String getFileDownloadType() {
return "expired";
}
}
public class TemplateMethodMain {
public static void main(String[] args) {
ExcelDataParser csvDataParser = new ExcelDataParser();
csvDataParser.parseDataAndGenerateFile();
}
}
But if you don't need a class for every type, you also could make the type a variable inside a single class and passing the type to the contructor
For example:
public class CsvFileHelper {
private final String fileDownloadType;
public CsvFileHelper(String type) {
fileDownloadType = type;
}
public void parseDataAndGenerateFile() {
createHeader();
generateFile();
}
public void createHeader() {
if ("expired".equals(fileDownloadType)) {
} else {
}
}
public void generateFile() {
if ("expired".equals(fileDownloadType)) {
} else {
}
}
}
public class TemplateMethodMain {
public static void main(String[] args) {
CsvFileHelper csvDataParser = new CsvFileHelper("expired");
csvDataParser.parseDataAndGenerateFile();
}
}
I also done this example creating object for both class and call the method is there anyway to override the baseclass?
class Car {
void Max() {
System.out.println("Audi");
}
}
class Speed extends Car {
void Max() {
System.out.println("300");
}
public static void main(String args[]) {
Speed s=new Speed();
s.Max();
}
}
At the risk of being called a "give me the repz" type person...hopefully this helps:
This first class is a BaseClass, you can create a new one by writing:
BaseClass myBaseClass = new BaseClass();
public class BaseClass {
private int aNumber; //This global variable is private and so cannot be overwritten.
int anotherNumber; //This global variable is package scope and so can be accessed by sub-classes in the same package.
protected yetAnotherNumber; //This variable is accessible by any subclasses.
public int numberAvailableToEveryone; //This global variable is accessible to anyone and everyone.
public BaseClass() {} //This is a constructor (no return type)
private void myPrivateMethod() {} //This method cannot be overwritten
void packageScopeMethod() {}
protected void thisMethodCanBeOverwrittenBySubClasses() {}
public void theWorldCanCallMe() {} //extendable to the world, not much different than protected scope tbh
}
Now, to overwrite a method you can create an anonymous class like so:
BaseClass myAnonymousClass = new BaseClass() {
public void theWorldCanCallMe() {
//in here you can override the method to do whatever you want.
}
}
or you could define a subclass like so:
public class SubClass extends BaseClass {
#Override
public void tehWorldCanCallMe() {
//again your new code goes here
}
}
and then instantiate it like so:
SubClass myClassThatOverridesAMethod = new SubClass();
A car example closer to your code:
class Car {
private String name;
int speed = 100;
Car(String name) { //This is the base classes constructor
this.name = name;
}
String max() {
return speed;
}
void run() {
System.out.println(name);
System.out.println(max()); //will print the base speed unless overridden
}
}
class Audi extends Car {
Audi() {
super("Audi")
}
}
class Speed extends Car {
Speed() {
super("Speed");
}
#Override
String max() {
speed = 300;
return speed;
}
public static void main(String args[]) {
Speed s=new Speed();
s.run();
}
}
I have an interface in which I declare an inner class:
public interface myInterface
{
int count();
public class myInterfaceInnerClass
{
public void testOverride()
{
}
}
}
And class Test implements myInterface:
public class Test implements myInterface
{
public Test()
{
// TODO Auto-generated constructor stub
}
public int count()
{
return 1;
}
//Here I would like to be able to override the inner class' method testOverride
}
Is it possible to override the inner class' method testOverride in class Test?
EDIT:
In response to comment made by O. Charlesworth, I came up with the following:
public interface myInterface
{
myInterface aInterface = new myInterfaceInnerClass();
int count();
public class myInterfaceInnerClass implements myInterface
{
#Override
public int count()
{
// TODO Auto-generated method stub
return 0;
}
public void testOverride()
{
}
}
}
In class Test:
public class Test implements myInterface
{
public Test()
{
// TODO Auto-generated constructor stub
}
public int count()
{
return 1;
}
}
Is it still possible to override the inner class' method testOverride
here in class Test?
Here's something you can do:
import myInterface.myInterfaceInnerClass;
public class Test extends myInterfaceInnerClass implements myInterface {
#Override public int count() {
// ...
return 0;
}
#Override
public void testOverride() {
// ...
}
}
Reason for extending class myInterfaceInnerClass (A picture > a million words):
(source: gyazo.com)
i'm trying to write anonymous inner class
interface Face{
void seeThis(String what);
}
class Eyes {
public void show(Face f){}
}
public class Seen {
public void test() {
Eyes e = new Eyes();
e.show(new Face() {
#Override
public void seeThis(String what){
System.out.print(what);
}
});
public static void main(String[] args) {
Seen s = new Seen();
s.test();
}
}
How to call seeThis() and how to pass parameter to it?
Method seeThis() belongs to Face class, which instance is anonymous and thus cannot be reached without storing reference to it. If you want to store a reference, you can do this in the following way:
public class Seen {
public Face face;
....
this.face = new Face() { ... };
e.show(this.face);
And then,
Seen s = new Seen();
s.face.seeThis();
Now, regarding passing the parameter. You have two options - declare parameter outside of anonymous class and make it final in order to be reachable by this anonymous class, or replace anonymous class with normal one and pass the parameter to its constructor:
Approach one:
final int parameter = 5;
...(new Face() {
#Override
public void seeThis() {
System.out.println(parameter);
}
});
Approach two:
public class MyFace implements Face() {
private final int parameter;
public MyFace(int parameter) {
this.parameter = parameter;
}
#Override
public void seeThis() {
System.out.println(parameter);
}
}
Then,
...
e.show(new MyFace(10));