I have the below code.
public class Test {
public static void main(String args[])
{
int i = 0;
if(i==0){
Beer obj = new Beer();
}
else {
Rum obj = new Rum();
}
System.out.println(obj.brand); //doesn't work
} }
class Drink {
}
class Beer extends Drink{
public String brand = "BeerBrand"; }
class Rum extends Drink{
public String brand = "RumBrand"; }
Is there an way to make the above work without using function overriding or dynamic class loading?
All classes are dynamically loaded in JVM there is no static loading like in C. Is this correct?
Drink should be an abstract class and provide an abstract member getBrand() or similar, overridden by Beer and Rum.
Then you'd do something like:
Drink d = null;
if (...) {
d = new Beer();
}
so you instantiate the reference appropriately. Because it's still of type Drink you can reference the brand. The Drink reference will let you access anything drink-able, and the implementation provides the specifics. Note that Drink is abstract, since you can't instantiate a Drink - you have to be more specific.
To answer your further questions, you could provide a base method and do something like:
if (this instanceof Beer) {
...
}
to avoid overriding. But why would you ?
To answer your second question, classes are dynamically loaded by the JVM upon reference. You can watch that occur by setting the -verbose flag on the JVM.
This code won't work because scope of 'obj' is only within if-else block.
You need to declare it above if-else block of type Drink.
Is there an way to make the above work without using function overriding or dynamic class loading?
The only alternative is to use reflections, but fixing the design of the classes would be much simpler/better
All classes are dynamically loaded in JVM there is no static loading like in C. Is this correct?
Yes. They can be dynamically loaded more than once and even unloaded.
Using an object orientated approach would look like this.
public class Test {
public static void main(String... args) {
Drink drink;
if (args.length == 0) {
drink = new Beer();
} else {
drink = new Rum();
}
System.out.println(drink.getBrand());
}
}
interface Drink {
public String getBrand();
}
class Beer implements Drink {
#Override
public String getBrand() {
return "BeerBrand";
}
}
class Rum implements Drink {
#Override
public String getBrand() {
return "RumBrand";
}
}
Related
I searched the whole StackOverflow website I come across only one nearest
answer but not working in my condition.
How can I call methods of two classes in each other
First Class is Alpha and calling a Function of Beta
public Class Alpha
{
Beta obj;
public Alpha()
{
obj = new Beta();
}
public void A()
{
print A;
obj.B();
}
}
Second Class is Beta and calling a function of Alpha
public Class Beta
{
Alpha obj;
public Beta()
{
obj = new Alpha();
}
public void B()
{
print B;
obj.A()
}
}
In Java/android, it shows StackOverflow exception. Due to the recursive call of constructors of each other.
How to avoid this Exception?
I have 15 Classes and each one is linked Cyclically.
Do I need to use parent class?
Or How I should use constructors to avoid StackOverflow Exception?
Here's a suggestion that will break the cycle: Specify one class as the parent and the other as the dependent.
Let's put Alpha in charge:
public class Alpha {
private Beta beta;
public Alpha() {
this.beta = new Beta(this);
}
}
Here's the child Beta:
public class Beta {
private Alpha alpha;
public Beta(Alpha parent) {
this.alpha = parent;
}
}
No more cycle.
You shall change your class Beta's definition to break the circular link between the two classes and creating their instances. It could be somewhat like this instead:
public class Beta {
Alpha obj;
public Beta() {
}
public void B() {
print B;
new Alpha().A();
}
}
Ideally, you shall not create instances of other classes unless you would want to access them.
The stack overflow is obvious; it's not just that the class definitions are cyclical; the constructors are recursive. The recursion is just "hidden" because they are in different classes. With any recursion, there must be some limit condition to break the recursion cycle. Without knowing the details of your problem -- why do you have this cyclical definition -- it's hard to give a solution. It really comes down to a question of code architecture. I can offer a few suggestions.
First, I generally dislike cyclical definitions. It leads to confusion and issues in doing code builds and ports. This can be avoided by using interfaces; maybe an empty marker interface. I would then take assignment of the internal objects out of the constructor, and make an explicit set() function, so that the caller has to initialize these:
public interface SomeInterface { }
public class Alpha implements SomeInterface
{
private SomeInterface obj;
public Alpha()
{}
public void setBeta (SomeInterface si)
{
obj = si;
}
}
public class Beta implements SomeInterface
{
private SomeInterface obj;
public Beta ()
{ }
public void setAlpha ( SomeInterface si )
{
obj = si;
}
}
In the calling code, you would have
Alpha a = new Alpha();
a.setBeta ( new Beta() );
I've got the following code example:
class p {
public void druckauftrag() {
// ...
drucke();
}
public void drucke() {
System.out.println("B/W-Printer");
}
}
class cp extends p {
public void drucke() {
System.out.println("Color-Printer");
}
}
Calling the following lines:
cp colorprinter = new cp();
cp.druckauftrag();
There is no problem understanding why "cp.druckauftrag();" results in console output "Color-Printer".
But when I call:
p drucker = (p)colorprinter;
drucker.druckauftrag();
I get the same output - why?
Does the typecast overwrite the object "drucker" 's method "drucke" with "drucke" from colorprinter?
Thanks in advance for every explanation.
colorprinter does not stop being an instance of cp when you use the cast operator on it, so its implementation of public void drucke() does not change
What you are expressing with your (p)colorprinter casting is the kind of contract (interface) you expect the object colorprinter to satisfy, which includes a public method with the signature public void drucke(), but not any specific implementation.
And, by the way, this casting is already performed implicitly when you declare drucker of the type p, so (p) is redundant in p drucker = (p)colorprinter;. p drucker = colorprinter; will suffice.
Here you can learn more about typecasting.
Keep in mind that it's best practice to extend from abstract classes or interfaces and only #Override (implement) abstract methods. A better design of your code would be:
abstract class BasePrinter {
public void druckauftrag() {
// ...
drucke();
}
public void drucke();
}
class p extends BasePrinter {
public void drucke() {
System.out.println("B/W-Printer");
}
}
class cp extends BasePrinter {
public void drucke() {
System.out.println("Color-Printer");
}
}
But of course constraints don't always allow for that kind of redesign. Passing the base requirements as parameters to the constructor (dependency injection) instead of extending a base class can also be a good alternative:
interface Druckable {
void drucke();
}
class Druckauftrager {
Druckable dk;
Druckauftrager(Drukable dk){
this.dk = dk;
}
public void druckauftrag() {
// ...
dk.drucke();
}
}
class p implements Druckable {
public void drucke() {
System.out.println("B/W-Printer");
}
}
class cp implements Druckable {
public void drucke() {
System.out.println("Color-Printer");
}
}
Now, if you want to express that a printer requires or can have multiple printing capabilities (like both color and b/w), you just write the class with as much extra Drukable properties and constructor parameters as you want, for example:
class BlackAndWhiteOrColorPrinter {
p blackAndWhitePrintService;
cp colorPrintService;
Druckable selectedPrintService;
BlackAndWhiteOrColorPrinter (p blackAndWhitePrintService, cp colorPrintService){
this.blackAndWhitePrintService = blackAndWhitePrintService;
this.colorPrintService = colorPrintService;
this.selectedPrintService = blackAndWhitePrintService;
}
public void druckauftrag() {
// ...
selectedPrintService.drucke();
}
}
This way, you can even write a class MultiPrinter with a MultiPrinter(List<Druckable> printServices) constructor and add any number of printing modes to its list of printing services: p, cp, and whatever other implementation of Druckable with its public void drucke() comes in the future. It is also extra practical if you want to introduce unit testing, so you can provide mockup objects that force the particular conditions you want to test, like druke() throwing a PaperJamException, for example.
For more information on how interfaces, overriding and inheritance work, see https://docs.oracle.com/javase/tutorial/java/IandI/usinginterface.html
BTW, acording to the latest revision of the official java code conventions guide and also by de facto standard, classes in Java should use CamelCase naming convention. You can also benefit greatly from using semanting naming on all your definitions, like BlackAndWhitePrinter blackAndWhitePrinter and ColorPrinter colorPrinter.
colorprinter is an instance of cp. Even when you upcast it to p, it's drucke() method will be still the one from cp.
The difference is that after you upcast colorprinter, you will not be able to invoke the methods that cp defines on its own.
When you create an object using new operator, memory is allocated in heap. Methods and fields are actually there depending upon the concrete actual class of the object.
Alter a sub class overrides and modifies a behavior from its super class, invoking the overridden method will always result in the modified behavior. Casting will only mean that the object of sub class is now represented by the super type as the object has a modified behavior for a method will always result in the modified behavior.
Suppose you have below classes
public class Fruit{
public void taste(){
System.out.println("depends upon the actual fruit");
}
}
public class Mango extends Fruit{
#Override
public void taste(){
System.out.println("sweet");
}
public void wayToExposeSuperMethod(){
super.taste();
}
}
In other words its like calling mango as a fruit but still mango remains mango.
For above code
Fruit fruit = new Mango();
fruit.taste(); // <-- this will output : sweet
((Mango)fruit).taste();// <-- this will output : sweet
fruit.wayToExposeSuperMethod(); // <-- this will not compile
((Mango)fruit).wayToExposeSuperMethod(); // <-- this will output : depends upon the actual fruit
I've seen this question asked in several ways, but the code is usually specific to the user, and I get lost a little. If I'm missing a nice clear and simple explanation, I'm sorry! I just need to understand this concept, and I've gotten lost on the repeats that I've seen. So I've simplified my own problem as much as I possibly can, to get at the root of the issue.
The goal is to have a main class that I ask for variables, and then have those user-inputted variables assessed by a method in a separate class, with a message returned depending on what the variables are.
import java.io.*;
public class MainClass {
public static void main(String[] args) {
InputStreamReader input = new InputStreamReader(System.in);
BufferedReader reader = new BufferedReader(input);
String A;
String B;
try {
System.out.println("Is A present?");
A = reader.readLine();
System.out.println("Is B present?");
B = reader.readLine();
Assess test = new Assess();
} catch (IOException e){
System.out.println("Error reading from user");
}
}
}
And the method I'm trying to use is:
public class Assess extends MainClass {
public static void main(String[] args) {
String A = MainClass.A;
String B = MainClass.B;
if ((A.compareToIgnoreCase("yes")==0) &&
((B.compareToIgnoreCase("yes")==0) | (B.compareToIgnoreCase("maybe")==0)))
{
System.out.println("Success!");
}
else {
System.out.println ("Failure");
}
}
}
I recognize that I'm not properly asking for the output, but I can't even get there and figure out what the heck I'm doing there until I get the thing to compile at all, and I can't do THAT until I figure out how to properly pass values between classes. I know there's fancy ways of doing it, such as with arrays. I'm looking for the conceptually simplest way of sending a variable inputted from inside one class to another class; I need to understand the basic concept here, and I know this is super elementary but I'm just being dumb, and reading what might be duplicate questions hasn't helped.
I know how to do it if the variable is static and declared globally at the beginning, but not how to send it from within the subclass (I know it's impossible to send directly from the subclass...right? I have to set it somehow, and then pull that set value into the other class).
In order to pass variables to an object you have either two options
Constructor - will pass parameter when creating the object
Mutator method - will pass parameters when you call the method
For example in your Main class:
Assess assess = new Assess(A, B);
Or:
Assess assess = new Assess();
assess.setA(A);
assess.setB(B);
In your Assess class you have to add a constructor method
public Assess(String A, String B)
Or setter methods
public void setA(String A)
public void setB(String B)
Also, Assess class should not extend the main class and contain a static main method, it has nothing to do with the main class.
Below there is a code example!
Assess.java
public class Assess {
private a;
private b;
public Assess(String a, String b) {
this.a = a;
this.b = b;
}
public boolean check() {
if ((A.compareToIgnoreCase("yes")==0) &&
((B.compareToIgnoreCase("yes")==0) ||
(B.compareToIgnoreCase("maybe")==0)))
{
System.out.println("Success!");
return true;
} else {
System.out.println ("Failure");
return false;
}
MainClass .java
public class MainClass {
public static void main(String[] args) {
InputStreamReader input = new InputStreamReader(System.in);
BufferedReader reader = new BufferedReader(input);
String A;
String B;
try {
System.out.println("Is A present?");
A = reader.readLine();
System.out.println("Is B present?");
B = reader.readLine();
Assess test = new Assess(A, B);
boolean isBothPresent = test.check();
// ................
} catch (IOException e){
System.out.println("Error reading from user");
}
}
I think what you're looking for are method parameters.
In a method definition, you define the method name and the parameters it takes. If you have a method assess that takes a string and returns an integer, for example, you would write:
public int assess(String valueToAssess)
and follow it with code to do whatever you wanted with valueToAssess to determine what integer you wanted to return. When you had decided that i was the int to return, you would put the statement
return i;
into the method; that terminates the method and returns that value to the caller.
The caller obtains the string to be assesed, then calls the method and passes in that string. So it's more of a push than a pull, if you see what I mean.
...
String a = reader.readLine();
int answer = assess(a);
System.out.println("I've decided the answer is " + answer);
Is that what you're looking for?
A subclass will have access to the public members of the superclass. If you want to access a member using {class}.{member} (i.e. MainClass.A) it needs to be statically declared outside of a method.
public class MainClass {
public static String A;
public static String B;
...
}
public class Subclass {
public static void main(String[] args) {
// You can access MainClass.A and MainClass.B here
}
}
Likely a better option is to create a class that has these two Strings as objects that can be manipulated then passed in to the Assess class
public class MainClass {
public String A;
public String B;
public static void main(String[] args) {
// Manipulate A, B, assign values, etc.
Assess assessObject = new Assess(A, B);
if (assessObject.isValidInput()) {
System.out.println("Success!");
} else {
System.out.println("Success!");
}
}
}
public class Assess {
String response1;
String response2;
public Assess (String A, String B) {
response1 = A;
response2 = B;
}
public boolean isValidInput() {
// Put your success/fail logic here
return (response1.compareToIgnoreCase("yes") == 0);
}
}
First you don't need inheritance. Have one class your main class contain main take the main out of Assess class. Create a constructor or setter methods to set the variables in the Assess class.
For instance.
public class MainClass
{
public static void main(String[] Args)
{
Assess ns = new Assess( );
ns.setterMethod(variable to set);
}
}
I'm not 100% sure of your problem, but it sounds like you just need to access variables that exist in one class from a subclass. There are several ways...
You can make them public static variables and reference them as you show in your Assess class. However, they are in the wrong location in MainClass use
public static String A, B;
You can make those variables either public or protected in the parent class (MainClass in your example). Public is NOT recommended as you would not know who or what modified them. You would reference these from the sub-class as if present in the sub-class.
public String A, B; // Bad practice, who modified these?
protected String A, B;
The method that might elicit the least debate is to make them private members and use "accessors" (getters and setters). This makes them accessible programmatically which lets you set breakpoints to catch the culprit that is modifying them, and also let you implement many patterns, such as observer, etc., so that modification of these can invoke services as needed. If "A" were the path to a log file, changing its value could also cause the old log to close and the new one to be opened - just by changing the name of the file.
private String A, B;
public setA(String newValue) {
A = newValue;
}
public String getA() {
return A;
}
BUT ...
Your question says "send to the subclass", but confounded by your knowing how to do this using global variables. I would say that the simplest way is to provide the values with the constructor, effectively injecting the values.
There are other ways, however, your example shows the assessment performed by the constructor. If your Assess class had a separate method to perform the assessment, you would just call that with the variables as arguments.
Your example is confusing since both classes have main methods and the child class does the assessing - I would think you would want the opposite - Have MainClass extend Assess, making "MainClass an Assess'or", let main assign the Strings to Assess' values (or pass them as arguments) to the parent class' "assess" method ("super" added for clarity):
super.setA(local_a);
super.setB(local_b);
super.assess();
or
super.assess(A, B);
I have an interface (p) and an implementation (imp). If I do the following in the code, then the check works:
if (!(imp instanceof p)) {
logger.error(imp.getClass().getName()+
" doesn't satisfy the interface "
+p.getClass().getName());
}
I tried to make it into a callable method as follows:
private boolean checkInterfaceImplementation(Object implemen, Object inter){
return (implemen instanceof inter);
}
which failed.
Then I found that inter needs to be a specific type and I cannot use a generic object. Then I found out about
"B.class.isAssignableFrom(A.getClass())"
Then I did:
System.out.println("B.class.isAssignableFrom(A
.getClass())");
The output was
true
I read up more from this question. My question is "Is this (the second implementation with ".isAssignableFrom") the preferred or standard way to implement said method? Is there any way that this present implementation can create problems?
It's hard to understand your question. I will edit when more details are received, if necessary, but as a general rule of thumb instanceof is an indicator of a lack of polymorphism and a design issue. Not always the case, but if you are a beginner I would try to use it as little as possible.
Instead, consider why that check is even there. If "imp" implements "p", then you are guaranteeing that any "imp" will have all the methods in "p". If it doesn't, you will receive a compiler error before you can even build. This is very abstract right now so I will do quick example.
public interface Runs {
public void run();
}
public class Cat implements Runs {
int numLegs;
public Cat() {
this.numLegs = 4;
}
public void run() {
System.out.println("does whatever running cats do");
}
}
public class Human implements Runs {
int numLegs;
public Human() {
this.numLegs = 2;
}
public void run() {
System.out.println("does whatever running humans do");
}
}
public class Main {
public static void main(String[] args) {
Cat cat = new Cat();
Human human = new Human();
ArrayList<Runs> listOfRunners = new ArrayList<Runs>();
listOfRunners.add(cat);
listOfRunners.add(human);
Runs runner = listOfRunners.get(0);
/* no compiler error because by implementing Runs we guarantee it has run() method */
runner.run();
runner = listOfRunners.get(1);
/* It doesn't matter what the object is. We don't care if it is cat or human */
runner.run();
}
}
Not sure exactly what you are trying to do, but something like this should work:
inter.getClass().isInstance(implemen)
Most likely what you are trying to do can be done in a much better way than resorting to this, though.
I am currently in the design mode for this problem:
Implement the Speaker interface that is predefined. Create three classes that implement Speaker in various ways. Create a driver class whose main method instantiates some of these objects and tests their abilities.
How would I go about designing this program and them moving into the coding stage. I want to use these three classes to implement the Speaker interface class: Politician, Lecturer, and Pastor class. The methods I want to use are:
public void speak();
public void announce (String str);
Now for my design and coding, how would I go about to declare and object reference variable and have that variable have multiple references?
It's simple really. In brief:
class ClassA implements Speaker
{
public void speak(){
System.out.println("I love Java") ; //implement the speak method
}
}
class ClassB implements Speaker //follow the example of ClassA
class ClassC implements Speaker //same as above
Speaker[] speakers = new Speakers{new ClassA(),new ClassB(),new ClassC()} ;
for(Speaker speaker: speakers)
speaker.speak(); //polymorphically call the speak() method defined in the contract.
See "What is an Interface?" http://docs.oracle.com/javase/tutorial/java/concepts/interface.html This will hopefully get you started with the basics you're looking for.
The start of the implementation would look something like the following...
class Politician implements Speaker
{
public void speak()
{
// Method implementation
}
public void announce (String str)
{
// Method implementation
}
}
class Lecturer implements Speaker
{
public void speak()
{
// Method implementation
}
public void announce (String str)
{
// Method implementation
}
}
class Lecturer implements Speaker
{
public void speak()
{
// Method implementation
}
public void announce (String str)
{
// Method implementation
}
}
public static void main(String [] args)
{
Speaker s1 = new Politician();
Speaker s2 = new Pastor();
Speaker s3 = new Lecturer();
// Do something...
}
Use a Factory Method Design Pattern.. Check this article at http://en.wikipedia.org/wiki/Factory_method_pattern
Your code could look something like this, if you use the Factory pattern
public class SpeakerFactory {
enum SpeakerEnum { POLITICIAN, LECTURER, PASTOR} ;
Speaker getSpeaker(SpeakerEnum speakerType) {
switch (speakerType) {
case POLITICIAN : return new Politician();
....
}
}
}