Design an interface named Colorable with a void method named howToColor().
Design a class named Triangle extending GeometricObject and implementing Colorable.
Triangle implements howToColor method to display the message "Color all three sides".
Triangle implements thetoString method to display its color and its sides.
In a triangle, the sum of any two sides is greater than the other side. The Triangle class must adhere to this rule. Create the TriangleException class, and complete and implement the constructor of the Triangle class to throw a TriangleException object if a triangle is created with sides that violate the rule.
The output of the test program should be as indicated below.
abstract class GeometricObject {
private String color = "white";
protected GeometricObject(String color) {
this.color = color;
}
public String toString() {
return "Color: " + color;
}
public abstract double getPerimeter();
}
class Triangle {
private double side1, side2, side3;
public Triangle(double side1, double side2, double side3) throws TriangleException {
}
}
class TriangleException {
}
Code is testing:
try {
Triangle t1 = new Triangle(1.5, 2, 3);
System.out.println(t1.toString());
System.out.println("Perimeter for t1: " + t1.getPerimeter());
t1.howToColor();
Triangle t2 = new Triangle(1, 2, 3);
System.out.println(t2.toString());
System.out.println("Perimeter for t2: " + t2.getPerimeter());
t2.howToColor();
} catch (TriangleException ex) {
System.out.println(ex.getMessage());
System.out.println("Side1: " + ex.getSide1());
System.out.println("Side2: " + ex.getSide2());
System.out.println("Side3: " + ex.getSide3());
}
According to this code result must be:
Color: red Sides: 1.5, 2.0, 3.0
Perimeter for t1: 6.5
Color all three sides.
Triangle inequality violation!
Side1: 1.0
Side2: 2.0
Side3: 3.0
So it must be true for the input in the example. For example for t2.getPerimeter() statement we have to create a getPerimeter method by return value of side1 + side2 + side3. But t2 part does not belong to us it belongs to the user.
I couldn't answer this question I need your help. In the first step, I got an error. I can solve other parts but I couldn't solve throws Exception part. I tested original version of code in Eclipse (without any changing) but I get a throws Exception error. If you try the code like me you will get error too. Now How can I solve this problem, I'm new in Java.
Replace class TriangleException with class TriangleException extends Exception. All user-defined exception should be subclasses of Exception.
Related
I'm really not too sure of how to say this but hopefully through showing the code someone might be able to help.
I'm trying to access the variable data in the semibreve which is an instance of the MainMusicNotesClass and then when i create a new class have it inherit the previous instance data and add on the new fields.
class MainMusicNoteValues {
String noteName;
double noteValue;
AssetImage? noteApperanace;
MainMusicNoteValues(this.noteName, this.noteValue, this.noteApperanace);
}
class MainNotes {
static final semibreve = MainMusicNoteValues(
"Semibreve", 4, const AssetImage('/assets/NoteValues/semibreve.png'));
}
class NVLiteracyNote extends MainMusicNoteValues {
int fastestTime;
int correct;
int incorrect;
NVLiteracyNote([this.correct = 0, this.incorrect = 0, this.fastestTime = 0])
: super('', 0.0, null);
//I understand that the super is the parent constructor and will determine the noteName, NoteValue and Appearance
}
Now I want to have the new variable (with the same name) in another class inherit the previous MainNotes.semibreve data and add on the new fields.
class NVNotes{
static final semibreve = NVLiteracyNote();
}
I'm thinking of how to take the MainNotes.semibreve data and pass in the noteName,noteValue and Appearance into the new NVNotes.semibreve.
Essentially at the end NVNotes.semibreve Should have the data:
noteName: 'Semibreve'
noteValue: 4.0
Appearance: const AssetImage('/assets/NoteValues/semibreve.png')
correct: 0
incorrect: 0
fastestTime: 0
I understand that this could be a terrible explanation of what i am trying to achieve but i would love any help.
I have a transformation which outputs a type with a wildcard: Feature<? extends Geomery>. I have specified a coder for this class and created a pipeline.
final Pipeline pipeline = Pipeline.create();
final TypeDescriptor<Feature<? extends Geometry>> featureTypeDescriptor =
new TypeDescriptor<Feature<? extends Geometry>>() {
};
pipeline.getCoderRegistry().registerCoderForType(featureTypeDescriptor, FeatureCoder.of());
final List<String> data = Arrays.asList("a", "b");
final PCollection<Feature<? extends Geometry>> features =
pipeline.apply(Create.of(data).withCoder(StringUtf8Coder.of()))
.apply(ParDo.of(new DoFn<String, Feature<? extends Geometry>>() {
#ProcessElement
public void process(ProcessContext processContext) {
final String name = processContext.element();
processContext.output(new FeatureImpl(name));
}
}));
pipeline.run().waitUntilFinish();
When I run this pipeline, I get the following error:
Exception in thread "main" java.lang.ClassCastException: org.apache.beam.sdk.repackaged.com.google.common.reflect.Types$WildcardTypeImpl cannot be cast to java.lang.reflect.TypeVariable
at org.apache.beam.sdk.coders.CoderRegistry.getCoderFromTypeDescriptor(CoderRegistry.java:623)
at org.apache.beam.sdk.coders.CoderRegistry.getCoderFromParameterizedType(CoderRegistry.java:656)
at org.apache.beam.sdk.coders.CoderRegistry.getCoderFromTypeDescriptor(CoderRegistry.java:618)
at org.apache.beam.sdk.coders.CoderRegistry.getCoder(CoderRegistry.java:252)
at org.apache.beam.sdk.values.PCollection.inferCoderOrFail(PCollection.java:149)
at org.apache.beam.sdk.values.PCollection.finishSpecifyingOutput(PCollection.java:89)
This can be traced back in the Beam code to the following line in org.apache.beam.sdk.coders.CoderRegistry#getCoderFromTypeDescriptor where type gets eventually assigned to ? extends Geometry:
else if (type instanceof WildcardType) {
// No coder for an unknown generic type.
throw new CannotProvideCoderException(
String.format("Cannot provide a coder for type variable %s"
+ " (declared by %s) because the actual type is unknown due to erasure.",
type,
((TypeVariable<?>) type).getGenericDeclaration()),
ReasonCode.TYPE_ERASURE);
}
The example below is a simplification of the real problem. In reality, I do not read from a list of strings but from HBase, so I cannot simply specify my coder in Create.of(data).withCoder(...). However, the behavior is the same.
Is this expected behavior and should I avoid using wild cards? Or should I approach this in another way? Why is my specified coder not used for this?
So I started learning Interfaces and now I'm wondering when to use
Interface i = new Class();
and when to use
Class c = new Class();
and I noticed that I can't use class methods if I do it the first way, only interface methods. Do you know why?
Sorry I'm still a noob in Java, Thanks for answering
Let me put it in simple way.
Interface defines the behavior of class and classes which implements interface will give implementations to that behavior.
Here is an example
Interface Shape
{
void draw();
}
Class Circle implements Shape
{
void draw()
{
... code to draw circle
}
void printRadius()
{
}
}
Class Rectangle implements Shape
{
void draw()
{
... code to draw rectangle
}
void printDiagonal()
{
}
}
now if you see same Shape Interface is implemented by 2 classes diffrently.
Now i can write like this
Shape shape = new Circle(); // This will allow you access only draw method
Circle circle = new Circle(); // This will allow you access all methods of circle
When you want your client/consumer to access only Shape specicfic methods like draw then use Shape shape = new Circle() else if you want Circle specific method such as printRadius then use Circle circle = new Circle()
The interfaces in OOP paradigm used to generalized common behavior across group of somewhat similar objects. Therefore then you using variable of more general type, e.g. interface you will be able to use only those common methods which interface defines. Since you should be able to assign to interface variable any of interface descendants (classes which implements given interface) and be able to work with it. Therefore while you assign
Interface i = new Class();
the only methods you will be able to access is those defined in the Interface. Additionally need to note, that variable will be dynamically binded to the runtime type, e.g. to the Class in your example, thus the calls for methods defined in you interface will be dispatched to the implementation of the class.
Also think of the following, for example you have definitions:
interface Vehicle {
public void drive();
public void stop();
}
Now if you write code:
Vehicle v = new BMW()
v.drive()
// do something else
v.stop()
it should behave same when you replace new BMW() with new Mitsubishi(), regardless the fact that probably in your BMW class you might have
class BMW {
public void listenMusic()
}
This is also called "Liskov substitution principle"
Liskov's notion of a behavioral subtype defines a notion of substitutability for objects; that is, if S is a subtype of T, then objects of type T in a program may be replaced with objects of type S without altering any of the desirable properties of that program.
This question already has answers here:
Should I initialize variable within constructor or outside constructor [duplicate]
(11 answers)
Closed 6 years ago.
What is the difference between below 2 ways of assigning values for variables of a class.
Class A{
Private Variable v = someValue;
}
vs
Class A{
private Variable v;
//constructor
public A(){
this.v = someValue;
}
}
Can someone please explain?
There is no real difference from a code execution point of view.
As a previous answer says, I prefer declaring the variable outside of the constructor; for example:
public class A {
private int aValue = 100;
}
Instead of
public class A {
private int aValue;
public A() {
this.aValue = 100;
}
}
The reason being that if you have multiple constructors, you do not have to keep writing this.aValue = 100; and you are unable to "forget" to initialize the variable in a constructor.
As others have said however, there are times when it is better to initialize the variable in the constructor.
If it will change based on values passed to it via the constructor, obviously initialize it there.
If the variable you are initializing may throw an error and you need to use try / catch - it is clearly better to initialize it in the constructor
If you are working on a team that uses a specific coding standard and they require you to initialize your variables in the constructor, you should do so.
Given freedom and none of the above, I still declare it at the top - makes it much easier to find all of your variables in one place (in my experience).
See this duplicate answer: https://stackoverflow.com/a/3919225/1274820
What is the difference between below 2 ways of assigning values for
variables of a class.
Generally nothing, but ...
class constructor is an entry point when creating a new instance, so all assignments should be done there for readability and maintainability.
When you want create a new instance you start reading a source code at the constructor. Here is an example. All informations about new instance are in one proper place.
public class C {
private int aValue;
private int bValue;
private int cValue;
private int dValue;
public C(int a, int b) {
this.aValue = a;
this.bValue = b;
this.cValue = a * b;
this.dValue = 1000;
}
}
If you look at the MSIL of this class:
namespace Demo
{
public class MyClass
{
private string str = "hello world";
private int b;
public MyClass(int b)
{
this.b = b;
}
}
}
.method public hidebysig specialname rtspecialname
instance void .ctor(int32 b) cil managed
{
// Code size 25 (0x19)
.maxstack 8
IL_0000: ldarg.0
IL_0001: ldstr "hello world"
IL_0006: stfld string Demo.MyClass::str <---- RIGHT HERE
IL_000b: ldarg.0
IL_000c: call instance void [mscorlib]System.Object::.ctor()
IL_0011: ldarg.0
IL_0012: ldarg.1
IL_0013: stfld int32 Demo.MyClass::b
IL_0018: ret
} // end of method MyClass::.ctor
You can see that the constructor is "injected" with the assignment of this.str = "hello world".
So once your code is compiled, there is no difference what so ever. Yet, there are quite a few good reasons why you should not do it (user1274820's answer has some them)
i have an application that is flexible, that the user can:
filter by any field
sort by any multiple of fields.
and because it will run in ASP.Net Site + some Xamarin C# Apps, i will also have paging in it.
For network performance, it will send projection on the required fields that will be shown.
So if i include in each "Service" method, a parameter "UQueryConstraints", that can send filter expression + oderBy expression + page numbers + Projection of the fields, to be used by the Repository, which will apply it to the DBContext, is this is going to be considered a Data leak to the domain services or not?
as seen in this Pic:
http://1drv.ms/1Ngi3Kn
e.g.:
notice:
"UQueryConstraints", it will not leak any "IQueryable".
The "AmbientDbContextLocator", from:
<http://mehdi.me/ambient-dbcontext-in-ef6/>
<https://github.com/mehdime/DbContextScope>
public class UIView
{
public static void Display()
{
object constraintsB = new UQueryConstraints<Car>().Filter(x => x.carNo <= 6).SortBy(x => x.eName).Page(1, 5);
//.Projection( field1, field2, field3)
Debug.WriteLine("---------------test CarModel -------------------");
CarModel carModel1 = new CarModel();
carModel1.printCars(constraintsB);
}
}
public class CarModel
{
private CarService _carService = new CarService();
void printCars(UQueryConstraints<Car> constraints)
{
foreach ( c in _carService.getCarsList("", constraints)) {
Debug.WriteLine("Reading from converted back: aName =" + c.aName + ", eName = " + c.eName);
}
}
}
public class CarService
{
public IList<Car> getCarsList(string Text, UQueryConstraints<Car> constraints)
{
object dbContextScopeFactory = new DbContextScopeFactory();
object ambientDbContextLocator = new AmbientDbContextLocator();
using (dbContextScope == dbContextScopeFactory.Create()) {
//after creating the Scope:
//1. create the repository
//2. call repository functions
object carRep = new CarRepository(ambientDbContextLocator);
return carRep.getCarsList("", constraints);
}
}
}
public class CarRepository : URepositoryFramwork.URepository
{
public CarRepository(IAmbientDbContextLocator contextLocator)
{
base.New(contextLocator);
}
public IList<Car> getCarsList(string Text, UQueryConstraints<Car> constraints)
{
object query = this.DataSet.Where(constraints.FilterExpression);
//.Select(constraints._projection2)
IList<Car> items;
if (constraints == null) {
items = query.ToList();
} else {
items = constraints.ApplyTo(query).ToList();
}
return items;
}
}
Regards.
Here are few points.
You don't need UQueryConstraints at all and you don't need to do any filtering in the UI at all.
I'd ague that the model is something that needs to be returned from the service so I wouldn't create CarModel in the UI layer and then pushed values to it, it doesn't make sense to me.
I'd have a method on the service that request some data and then returns it in some shape or form to the UI.
I'd inject the service to UIView.
I don't understand why there's so much noise around the context and why do you create it in getCarsList it seems like getCarList should be a class called RequestCars and both the repository and the service should be removed in favor of something like depicted in the command pattern.
I don't like the whole abstraction here at all, seems like over engineering to me and who says that IQueryable should be abstracted? it's like abstracting language/framework features whereas you should abstract domain features and only when necessary.
Abstracting 3rd-party frameworks can be fine to some extent but this isn't one of these cases.