In Javadoc, I can see Class ClassCastException's Constructor with String parameter. But ClassCastException's Instance automatically is created (by JVM), I don't know how to use ClassCastException's Constructor.
In my code, I want to get a result "wrong", not "B cannot be cast to C".
class Prac {
public static void main(String[] args) {
try {
ClassCastException e = new ClassCastException("wrong");
A a = new B();
C c = (C)a;
}
catch(ClassCastException e) {
System.out.println(e.getMessage());
}
}
}
class A {
}
class B extends A {
}
class C extends A{
}
Result : B cannot be cast to C
If you want the result "wrong", then just print "wrong".
public static void main(String[] args) {
try {
A a = new B();
C c = (C)a;
}
catch(ClassCastException e) {
System.out.println("wrong");
}
}
No need to go tinkering around with the exception.
Related
I'm struggling to make a mapping from class B to any subclass of A. See code below. It seems it is not possible with ModelMapper, since it ignores converter if it is not exact match. Could you recommend some similar library that is capable of this? Or any recommendation how to do similar behavior, without specifying all possible subclasses explicitly. Thanks a lot.
package com.randakm.p2plibrary.service.main;
import org.modelmapper.Converter;
import org.modelmapper.ModelMapper;
import org.modelmapper.spi.MappingContext;
public class ServiceMain {
/**
* #param args
*/
public static void main(String[] args) {
ModelMapper mapper = new ModelMapper();
mapper.addConverter(new B2AConverter());
B b = new B();
b.b = "some value";
A a = mapper.map(b, AA.class);
System.out.println("a: "+a.a); // I expect this to have the value from b
}
}
abstract class A {
String a;
}
class AA extends A {
String aa;
}
class AAA extends A {
String aaa;
}
class B {
String b;
}
class B2AConverter implements Converter<B, A> {
#Override
public A convert(MappingContext<B, A> context) {
B b = context.getSource();
A a;
try {
a = context.getDestinationType().newInstance();
a.a = b.b;
return a;
} catch (InstantiationException | IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
This question already has answers here:
What is a StackOverflowError?
(16 answers)
Closed 4 years ago.
Below is a program given for assignment. Request you to help on the below output getting as "Expected output". It providing error as "Exception in thread "main" java.lang.StackOverflowError".
class A
{
{
new B();
}
static class B
{
{
new A().new C();
}
}
class C
{
{
System.out.println("Expected output");
}
}
}
public class MainClass
{
public static void main(String[] args)
{
new A();
}
}
You call new A(), which calls new B(), which calls new A() again, which calls new B() again, and it goes on and on until you can't create new objects anymore (thus StackOverflowError).
You should stop creating A() or B() at some point
class A
{
{
new B();
}
static class B
{
static {
new A().new C();
}
}
class C
{
{
System.out.println("Expected output");
}
}
}
public class MainClass
{
public static void main(String[] args)
{
new A();
}
}
The Anonymous block is executed before any of the constructor
static block is executed before loading a static class
I don't know how to describe the question exactly, sorry!
I have a class(E) base on a base class(B) , and in a helper class(Printer) ,two same name methods (printIt).
These printIt methods use B or E as parameter, this is static polymorphism.
public class B {
public void printMe(){
System.out.println("i am b");
}
}
public class E extends B {
#Override
public void printMe(){
System.out.println("i am e");
}
}
public class Printer {
public void printIt(B b) {
System.out.println("it is b");
}
// public void printIt(B b) {
// if (b.getClass().equals(B.class)) {
// System.out.println("it is b");
// } else if (b.getClass().equals(E.class)) {
// E e = (E) b;
// printIt(e);
// }
// }
public void printIt(E e) {
System.out.println("it is e");
}
public static void main(String[] args) {
B b = new B();
E e = new E();
B be = e;
System.out.println("------------dynamic polymorphism ---------------");
b.printMe(); //i am b
e.printMe(); //i am e
be.printMe(); //i am e
System.out.println("------------static polymorphism ----------------");
Printer printer = new Printer();
printer.printIt(b); //it is b
printer.printIt(e); //it is e
System.out.println("-------------????????????????? -----------------");
printer.printIt(be); //it is b
}
}
In above code, the last printIt call will use "public void printIt(E e)" method to print " it is b ". But "be" variable is a "E" object in fact , is there a way in "Printer" let java to choice method according to the class of object passed in.
If i switch comments on "printIt(B b)" in above code, i wil get what i want, but is it tedious, because if I add many subclass of "B", i have to add many else if in it.
It Seems to me that you simply don't understand the basic ideas behind polymorphism properly. You were completely on the right track but got lost when writing the the printer class which should look like this:
public class Printer {
public void printIt(B b) {
b.printMe();
}
}
This is a very everyday use of polymorphism that seems to perfectly fill your need?
It is best to avoid these kinds of overloads. Where one parameter is a parent of the other.
It is up to the caller to pick which method gets called, which could easily break encapsulation:
printer.printIt(be); //it is b
printer.printIt((E) be); //it is e
Checking the dynamic type of be incurs extra runtime cost, so it is not done by default.
You could implement it yourself however:
class Printer {
private static final Map<Class<?>, BiConsumer<Printer, ?>> map = new HashMap<>();
private static final BiConsumer<Printer, B> defaultConsumer = (p, b) -> System.out.println("it is b");
static {
for(Method m : Printer.class.getDeclaredMethods()) {
if(m.getName().equals("printIt")) {
Class<?>[] params = m.getParameterTypes();
if(params.length == 1 && !params[0].equals(B.class)) {
map.put(params[0], (p, b) -> {
try {
m.invoke(p, b);
} catch (Exception e) {
// Should never happens
throw new RuntimeException("Invalid method mapping");
}
});
}
}
}
}
#SuppressWarnings("unchecked")
public <T> void printIt(B b) {
((BiConsumer<Printer, T>) map.getOrDefault(b.getClass(), defaultConsumer)).accept(this, (T) b);
}
public void printIt(E e) {
System.out.println("it is e");
}
}
I need to know the output of this code. But it's not working. Maybe the code is wrong.
I'm still learning how to use Java, and I tried fixing this for hours but still no luck.
Here is the code:
public class A
{
public A()
{
System.out.println ("A");
}
}
public class B extends A
{
public B()
{
System.out.println ("B");
}
}
public class C extends B
{
public C()
{
System.out.println ("C");
}
}
public static void main(String args[]) {
A a = new A();
B b = new B();
C c = new C();
}
Can anyone tell me what is wrong or missing in the code?
Put your main method in a class.
Filename : DemoClass.java
class A
{
public A()
{
System.out.println ("A");
}
}
class B extends A
{
public B()
{
System.out.println ("B");
}
}
class C extends B
{
public C()
{
System.out.println ("C");
}
}
public class DemoClass {
public static void main(String args[]) {
A a = new A();
B b = new B();
C c = new C();
}
}
Another point here is, you can have only public class in a file, so your A B and C all class can't be public in same java file.
Your java file name must be same as public class name. i.e. here DemoClass is public class so file name will be DemoClass.java
Java doc for getting started : getting started with java
For example:
public class Example {
public static void main(String...args) {
new C();
}
public static class A {
public A() {
System.out.println("A");
}
}
public static class B extends A {
public B() {
System.out.println("B");
}
}
public static class C extends B {
public C() {
System.out.println("C");
}
}
}
Also note that this might not print what you would expect. It would actually print:
A
B
C
Why? Constructors are always chained to the super class.
You can, but it is not recommended, nest your classes in a file. It is perfectly valid.
Notice in the output below that each successive child calls its parent's default constructor (super()) implicitly.
I recommend you create the files: A.java, B.java, C.java, and InheritenceTest.java.
public class InheritenceTest {
public class A {
public A() {
System.out.println("A");
}
}
public class B extends A {
public B() {
System.out.println("B");
}
}
public class C extends B {
public C() {
System.out.println("C");
}
}
public static void main(String args[]) {
InheritenceTest i = new InheritenceTest();
A a = i.new A();
B b = i.new B();
C c = i.new C();
}
}
Output:
A
A
B
A
B
C
Warning:
You shouldn't have more than 1 public classes in 1 java file, not recommended. However, it could still work if you didn't use the 'public' identifier (or by using static or inside another class). But for a starter, I would recommend you to have them all in separate files.
Error:
Your main method does not belong to any class. I propose you create another class that includes the public static void main method to test your application.
Info: keep a look at inheritance as your printings might not be what you expect. (Constructor of class B calls the constructor of A, and constructor of class C calls the constructor B which in turn calls the constructor of A).
That's why you get
A
A
B
A
B
C
*due to A() it prints A, then due to B() it prints A B and finally due to C() it prints A B C.
In your case, I would try the following:
//Filename: A.java
public class A {
public A() {
System.out.println ("A");
}
}
//Filename: B.java
public class B extends A {
public B() {
System.out.println ("B");
}
}
//Filename: C.java
public class C extends B {
public C() {
System.out.println ("C");
}
}
//Filename: Test.java
//use a Test class for testing
public class Test {
public static void main(String args[]) {
A a = new A();
B b = new B();
C c = new C();
}
}
if you have the following
Interface: Meal
Hotdog implements Meal
Burger implements Meal
Salad implements Meal
How would you create a method to take in one of these object types to return the appropriate object?
Example:
Method makeFood(HotDog)
if(HotDog instanceof Meal)
return new HotdogObject();
How do you correctly do this?
I'm working with
static public Food createMeal(Meal f)
throws Exception
{
if (f instanceof Hotdog)
{
return f = new HotDog();
}
if (f instanceof Burger)
{
return f = new Burger();
}
throw new Exception("NotAFood!");
}
Mostly you are confusing classes with their instances. The instanceof operator, as its name says, verifies that an object is an instance of a class, not that a class is a subclass of another. Your particular problem would be solved most elegantly by resorting to reflection:
public static <T extends Meal> T createMeal(Class<T> c) {
try { return c.newInstance(); }
catch (Exception e) { throw new RuntimeException(e); }
}
For example, if you want a Burger, you call
Burger b = createMeal(Burger.class);
But, if you really wanted just another instance of the same type as an instance that you already have, then the code would be
public static Meal createMeal(Meal x) {
try { return x.getClass().newInstance(); }
catch (Exception e) { throw new RuntimeException(e); }
}
If I understand correctly you want something like this?
if(f.getClass().isAssignableFrom(HotDog.class))
return new HotdogObject();
I guess you are referring to reflection.
look at this link
http://java.sun.com/developer/technicalArticles/ALT/Reflection/
import java.lang.reflect.*;
public class constructor2 {
public constructor2()
{
}
public constructor2(int a, int b)
{
System.out.println(
"a = " + a + " b = " + b);
}
public static void main(String args[])
{
try {
Class cls = Class.forName("constructor2");
Class partypes[] = new Class[2];
partypes[0] = Integer.TYPE;
partypes[1] = Integer.TYPE;
Constructor ct
= cls.getConstructor(partypes);
Object arglist[] = new Object[2];
arglist[0] = new Integer(37);
arglist[1] = new Integer(47);
Object retobj = ct.newInstance(arglist);
}
catch (Throwable e) {
System.err.println(e);
}
}
}
Try out the Class's class method : static Class<?> forName(String class_name)
for returning the object of the class that matches the instanceof condition.