• Log InLog In
  • Register
Liquid`
Team Liquid Liquipedia
EDT 03:19
CEST 09:19
KST 16:19
  • Home
  • Forum
  • Calendar
  • Streams
  • Liquipedia
  • Features
  • Store
  • EPT
  • TL+
  • StarCraft 2
  • Brood War
  • Smash
  • Heroes
  • Counter-Strike
  • Overwatch
  • Liquibet
  • Fantasy StarCraft
  • TLPD
  • StarCraft 2
  • Brood War
  • Blogs
Forum Sidebar
Events/Features
News
Featured News
[ASL19] Finals Recap: Standing Tall10HomeStory Cup 27 - Info & Preview18Classic wins Code S Season 2 (2025)16Code S RO4 & Finals Preview: herO, Rogue, Classic, GuMiho0TL Team Map Contest #5: Presented by Monster Energy6
Community News
Weekly Cups (June 30 - July 6): Classic Doubles4[BSL20] Non-Korean Championship 4x BSL + 4x China9Flash Announces Hiatus From ASL66Weekly Cups (June 23-29): Reynor in world title form?14FEL Cracov 2025 (July 27) - $8000 live event22
StarCraft 2
General
The GOAT ranking of GOAT rankings How Esports Is Reshaping the Future of Competitive Weekly Cups (June 30 - July 6): Classic Doubles The SCII GOAT: A statistical Evaluation Weekly Cups (June 23-29): Reynor in world title form?
Tourneys
RSL: Revival, a new crowdfunded tournament series FEL Cracov 2025 (July 27) - $8000 live event Sparkling Tuna Cup - Weekly Open Tournament WardiTV Mondays Korean Starcraft League Week 77
Strategy
How did i lose this ZvP, whats the proper response Simple Questions Simple Answers
Custom Maps
[UMS] Zillion Zerglings
External Content
Mutation # 481 Fear and Lava Mutation # 480 Moths to the Flame Mutation # 479 Worn Out Welcome Mutation # 478 Instant Karma
Brood War
General
i aint gon lie to u bruh... BGH Auto Balance -> http://bghmmr.eu/ ASL20 Preliminary Maps [ASL19] Finals Recap: Standing Tall SC uni coach streams logging into betting site
Tourneys
[BSL20] Non-Korean Championship 4x BSL + 4x China [BSL20] Grand Finals - Sunday 20:00 CET CSL Xiamen International Invitational The Casual Games of the Week Thread
Strategy
Simple Questions, Simple Answers I am doing this better than progamers do.
Other Games
General Games
Nintendo Switch Thread Stormgate/Frost Giant Megathread Path of Exile What do you want from future RTS games? Beyond All Reason
Dota 2
Official 'what is Dota anymore' discussion
League of Legends
Heroes of the Storm
Simple Questions, Simple Answers Heroes of the Storm 2.0
Hearthstone
Heroes of StarCraft mini-set
TL Mafia
TL Mafia Community Thread Vanilla Mini Mafia
Community
General
Stop Killing Games - European Citizens Initiative Summer Games Done Quick 2025! US Politics Mega-thread Russo-Ukrainian War Thread Summer Games Done Quick 2024!
Fan Clubs
SKT1 Classic Fan Club! Maru Fan Club
Media & Entertainment
Anime Discussion Thread [Manga] One Piece [\m/] Heavy Metal Thread
Sports
Formula 1 Discussion 2024 - 2025 Football Thread NBA General Discussion TeamLiquid Health and Fitness Initiative For 2023 NHL Playoffs 2024
World Cup 2022
Tech Support
Computer Build, Upgrade & Buying Resource Thread
TL Community
The Automated Ban List
Blogs
momentary artworks from des…
tankgirl
Culture Clash in Video Games…
TrAiDoS
from making sc maps to makin…
Husyelt
StarCraft improvement
iopq
Customize Sidebar...

Website Feedback

Closed Threads



Active: 662 users

The Big Programming Thread - Page 767

Forum Index > General Forum
Post a Reply
Prev 1 765 766 767 768 769 1031 Next
Thread Rules
1. This is not a "do my homework for me" thread. If you have specific questions, ask, but don't post an assignment or homework problem and expect an exact solution.
2. No recruiting for your cockamamie projects (you won't replace facebook with 3 dudes you found on the internet and $20)
3. If you can't articulate why a language is bad, don't start slinging shit about it. Just remember that nothing is worse than making CSS IE6 compatible.
4. Use [code] tags to format code blocks.
Acrofales
Profile Joined August 2010
Spain17971 Posts
September 24 2016 11:21 GMT
#15321
On September 24 2016 19:55 Prillan wrote:
Show nested quote +
On September 24 2016 18:03 spinesheath wrote:

int fizz, bar;

public void foo(int bar) { // this is where it could show a warning that bar is shadowing this.bar

int fizz; // this is where it could show a warning that fizz is shadowing this.fizz

// ... enough code to make you forget the line above ...

fizz = 5; // here you could mean to assign to this.fizz, introducing a bug

// and if we have some slightly more complex code with say loops, you might not even get a
// "value assigned to variable is never used" warning
}


One reason why I like the explicit self in python.


def method(self, bar):
... code here ...


I don't see how that solves anything. And you have the global scope as well.
spinesheath
Profile Blog Joined June 2009
Germany8679 Posts
Last Edited: 2016-09-24 11:39:26
September 24 2016 11:37 GMT
#15322
On September 24 2016 18:22 Acrofales wrote:
Show nested quote +
On September 24 2016 18:03 spinesheath wrote:

int fizz, bar;

public void foo(int bar) { // this is where it could show a warning that bar is shadowing this.bar

int fizz; // this is where it could show a warning that fizz is shadowing this.fizz

// ... enough code to make you forget the line above ...

fizz = 5; // here you could mean to assign to this.fizz, introducing a bug

// and if we have some slightly more complex code with say loops, you might not even get a
// "value assigned to variable is never used" warning
}


Yeah, ok. That's pretty bad. Anybody using shadowing like that is asking for it, though

I mean, I'm not a fan of shadowing in general and never use it, except in the constructor to initialize fields. And that goes at the bottom of the constructor, so any operations you do before just setting the field aren't affected b the potential bugs you describe.

Even if someone is aware of this possibility there still might be a time where he accidentally runs into that issue. Especially if the code for that class is modified well after it was first created.

Treat shadowing as a warning/error, use naming conventions that let you avoid all shadowing and you will have one less potential problem to worry about.

Though it certainly should be possible to create a more sophisticated shadowing warning rule that reports all shadowing except for simple initialization from the constructor.
If you have a good reason to disagree with the above, please tell me. Thank you.
Prillan
Profile Joined August 2011
Sweden350 Posts
September 24 2016 14:35 GMT
#15323
On September 24 2016 20:21 Acrofales wrote:
Show nested quote +
On September 24 2016 19:55 Prillan wrote:
On September 24 2016 18:03 spinesheath wrote:

int fizz, bar;

public void foo(int bar) { // this is where it could show a warning that bar is shadowing this.bar

int fizz; // this is where it could show a warning that fizz is shadowing this.fizz

// ... enough code to make you forget the line above ...

fizz = 5; // here you could mean to assign to this.fizz, introducing a bug

// and if we have some slightly more complex code with say loops, you might not even get a
// "value assigned to variable is never used" warning
}


One reason why I like the explicit self in python.


def method(self, bar):
... code here ...


I don't see how that solves anything. And you have the global scope as well.


The point is that, if you want to set a variable on the object, you have to use self. So if you find

def method(self):
foo = 1

it won't set foo on self but rather the local, newly declared variable, foo.

Setting variables in the global scope is an abomination, in all languages, and should be killed. Reading them can be permitted.

What this results in is that if you assign a variable inside a function, it will always create a local variable with that name. If you want to set a field on an object, you use x.foo = bar.


I'm not saying it's perfect. But at least it makes setting variables consistent whereas in other languages foo = bar could mean two different things depending on if the object has a field called foo or not.
TheBB's sidekick, aligulac.com | "Reality is frequently inaccurate." - Douglas Adams
RoomOfMush
Profile Joined March 2015
1296 Posts
September 24 2016 14:36 GMT
#15324
On September 24 2016 20:37 spinesheath wrote:
Show nested quote +
On September 24 2016 18:22 Acrofales wrote:
On September 24 2016 18:03 spinesheath wrote:

int fizz, bar;

public void foo(int bar) { // this is where it could show a warning that bar is shadowing this.bar

int fizz; // this is where it could show a warning that fizz is shadowing this.fizz

// ... enough code to make you forget the line above ...

fizz = 5; // here you could mean to assign to this.fizz, introducing a bug

// and if we have some slightly more complex code with say loops, you might not even get a
// "value assigned to variable is never used" warning
}


Yeah, ok. That's pretty bad. Anybody using shadowing like that is asking for it, though

I mean, I'm not a fan of shadowing in general and never use it, except in the constructor to initialize fields. And that goes at the bottom of the constructor, so any operations you do before just setting the field aren't affected b the potential bugs you describe.

Even if someone is aware of this possibility there still might be a time where he accidentally runs into that issue. Especially if the code for that class is modified well after it was first created.

Treat shadowing as a warning/error, use naming conventions that let you avoid all shadowing and you will have one less potential problem to worry about.

Though it certainly should be possible to create a more sophisticated shadowing warning rule that reports all shadowing except for simple initialization from the constructor.

Eclipse already has a build in warning for local variables shadowing fields with optional warnings for within constructors & setters. Furthermore there is a warning for fields shadowing inherited fields of super classes. The different syntax highlighting for fields and local variables is enabled by default too so unless you explicitly change it you should always see the difference when working with a local variable compared to a field.

But I dont like naming parameters the same as fields either. I usually give parameters long and descriptive names while fields get abbreviated forms. Doesnt always work though.
Manit0u
Profile Blog Joined August 2004
Poland17244 Posts
September 24 2016 14:55 GMT
#15325
On September 24 2016 23:36 RoomOfMush wrote:
Show nested quote +
On September 24 2016 20:37 spinesheath wrote:
On September 24 2016 18:22 Acrofales wrote:
On September 24 2016 18:03 spinesheath wrote:

int fizz, bar;

public void foo(int bar) { // this is where it could show a warning that bar is shadowing this.bar

int fizz; // this is where it could show a warning that fizz is shadowing this.fizz

// ... enough code to make you forget the line above ...

fizz = 5; // here you could mean to assign to this.fizz, introducing a bug

// and if we have some slightly more complex code with say loops, you might not even get a
// "value assigned to variable is never used" warning
}


Yeah, ok. That's pretty bad. Anybody using shadowing like that is asking for it, though

I mean, I'm not a fan of shadowing in general and never use it, except in the constructor to initialize fields. And that goes at the bottom of the constructor, so any operations you do before just setting the field aren't affected b the potential bugs you describe.

Even if someone is aware of this possibility there still might be a time where he accidentally runs into that issue. Especially if the code for that class is modified well after it was first created.

Treat shadowing as a warning/error, use naming conventions that let you avoid all shadowing and you will have one less potential problem to worry about.

Though it certainly should be possible to create a more sophisticated shadowing warning rule that reports all shadowing except for simple initialization from the constructor.

Eclipse already has a build in warning for local variables shadowing fields with optional warnings for within constructors & setters. Furthermore there is a warning for fields shadowing inherited fields of super classes. The different syntax highlighting for fields and local variables is enabled by default too so unless you explicitly change it you should always see the difference when working with a local variable compared to a field.

But I dont like naming parameters the same as fields either. I usually give parameters long and descriptive names while fields get abbreviated forms. Doesnt always work though.


You should always assume that someone might be looking at your code through vim or something and won't get all the IDE syntax sugar. As was stated previously, relying on smart IDE features to help with unclear code is a bad idea. It's pretty close to code obfuscation.
Time is precious. Waste it wisely.
RoomOfMush
Profile Joined March 2015
1296 Posts
September 24 2016 17:12 GMT
#15326
On September 24 2016 23:55 Manit0u wrote:
Show nested quote +
On September 24 2016 23:36 RoomOfMush wrote:
On September 24 2016 20:37 spinesheath wrote:
On September 24 2016 18:22 Acrofales wrote:
On September 24 2016 18:03 spinesheath wrote:

int fizz, bar;

public void foo(int bar) { // this is where it could show a warning that bar is shadowing this.bar

int fizz; // this is where it could show a warning that fizz is shadowing this.fizz

// ... enough code to make you forget the line above ...

fizz = 5; // here you could mean to assign to this.fizz, introducing a bug

// and if we have some slightly more complex code with say loops, you might not even get a
// "value assigned to variable is never used" warning
}


Yeah, ok. That's pretty bad. Anybody using shadowing like that is asking for it, though

I mean, I'm not a fan of shadowing in general and never use it, except in the constructor to initialize fields. And that goes at the bottom of the constructor, so any operations you do before just setting the field aren't affected b the potential bugs you describe.

Even if someone is aware of this possibility there still might be a time where he accidentally runs into that issue. Especially if the code for that class is modified well after it was first created.

Treat shadowing as a warning/error, use naming conventions that let you avoid all shadowing and you will have one less potential problem to worry about.

Though it certainly should be possible to create a more sophisticated shadowing warning rule that reports all shadowing except for simple initialization from the constructor.

Eclipse already has a build in warning for local variables shadowing fields with optional warnings for within constructors & setters. Furthermore there is a warning for fields shadowing inherited fields of super classes. The different syntax highlighting for fields and local variables is enabled by default too so unless you explicitly change it you should always see the difference when working with a local variable compared to a field.

But I dont like naming parameters the same as fields either. I usually give parameters long and descriptive names while fields get abbreviated forms. Doesnt always work though.


You should always assume that someone might be looking at your code through vim or something and won't get all the IDE syntax sugar. As was stated previously, relying on smart IDE features to help with unclear code is a bad idea. It's pretty close to code obfuscation.

I dont quite agree. The people who like to use an IDE will use an IDE. Those who dont like to use it better man up and learn how to deal with code like that. The editor / IDE you use is a tool. If it doesnt help you then you chose the wrong tool. Choose the right tool and you wont have a problem.

I dont blame nail manufacturers because I cant use a screwdriver to screw the nails into my walls. Its my job to get a hammer.
spinesheath
Profile Blog Joined June 2009
Germany8679 Posts
September 24 2016 17:25 GMT
#15327
A nail isn't quite the type of product that is modified by multiple people during its lifetime.

You know how you somtimes are forced to go to car repair shops that specialize on your kind of car instead of just any mechanic because fixing your car requires special tools? If you can increase the number of supported tools at next to no cost, you should go for it. Unless you want to boost the market share of your favorite IDE.
If you have a good reason to disagree with the above, please tell me. Thank you.
phar
Profile Joined August 2011
United States1080 Posts
September 24 2016 17:48 GMT
#15328
Use final (or const). Gets you halfway there, assuming you aren't passing around weird mutable objects.
Who after all is today speaking about the destruction of the Armenians?
Deleted User 3420
Profile Blog Joined May 2003
24492 Posts
September 25 2016 15:11 GMT
#15329
im not sure if this is a java specific question or not

but when do you want to use try/catch blocks instead of if(condition) { throw exception() } ?

is it only for checked instead of unchecked exceptions or is it more complicated than that?
RoomOfMush
Profile Joined March 2015
1296 Posts
Last Edited: 2016-09-25 15:39:17
September 25 2016 15:36 GMT
#15330
On September 26 2016 00:11 travis wrote:
im not sure if this is a java specific question or not

but when do you want to use try/catch blocks instead of if(condition) { throw exception() } ?

is it only for checked instead of unchecked exceptions or is it more complicated than that?

The simple answer: You use a try / catch block when you need it.

The better answer: You should build your software in a way that you never need a try / catch block unless when interfacing with third party systems or using native resources.

A try / catch block indicates that the programmer knows the code within the try block might throw an exception. In general this should only happen (a) when you use a method improperly, (b) when you dont know what the code will actually do (because you load it dynamically) or (c) when you use system components that might randomly fail (reading files from the OS when you dont have access, networking, etc).

Obviously you should always use third party libraries (or even your own code) correctly so the first of the above 3 "reasons" isnt a good reason at all. The other 2 reasons are unavoidable.

Examples:
B) You allow the user to customize your software with a plugin system. Users may write their own plugins, load them into the application and have them perform tasks. As the developer of your application it is impossible for you to know what exactly those plugins do and they might throw exceptions if they are nor properly written. For this reason you wrap all calls to the plugin system in try / catch blocks to make sure your application doesnt crash randomly because of faulty plugins.

C) You connect to a server to request certain data to be used by your application. The network might always randomly fail and a connection may be lost at any point in time. To make sure your application doesnt crash in these situations you wrap the networking code into try / catch blocks. When an exception is caught you display error dialogs to the user to let him know the connection was lost and he has to try again.


Edit:
By the way, even though it is possible you should NEVARR use exception to control the flow of your application. At least not in java. The performance of exceptions is horrendous compare to if/then/else statements. Every time an exception is generated the entire stack has to be traversed backwards to build the stacktrace. It also has to read all kinds of debug information from the .class files to generate a proper error message.
Acrofales
Profile Joined August 2010
Spain17971 Posts
September 25 2016 15:40 GMT
#15331
On September 26 2016 00:11 travis wrote:
im not sure if this is a java specific question or not

but when do you want to use try/catch blocks instead of if(condition) { throw exception() } ?

is it only for checked instead of unchecked exceptions or is it more complicated than that?

Your question isn't clear. The effect of trying something and then catching the exception is not the same as the effect of checking a condition and throwing an exception. In fact, they are almost the exact opposite, and complement one another.

In general, you want to throw an exception when you know something can go wrong, but how to deal with that is not the responsibility of that part of the code. You throw an exception so that the calling code can deal with that in a try... catch block.
Manit0u
Profile Blog Joined August 2004
Poland17244 Posts
September 25 2016 16:01 GMT
#15332
On September 26 2016 00:36 RoomOfMush wrote:
Show nested quote +
On September 26 2016 00:11 travis wrote:
im not sure if this is a java specific question or not

but when do you want to use try/catch blocks instead of if(condition) { throw exception() } ?

is it only for checked instead of unchecked exceptions or is it more complicated than that?

The simple answer: You use a try / catch block when you need it.

The better answer: You should build your software in a way that you never need a try / catch block unless when interfacing with third party systems or using native resources.

A try / catch block indicates that the programmer knows the code within the try block might throw an exception. In general this should only happen (a) when you use a method improperly, (b) when you dont know what the code will actually do (because you load it dynamically) or (c) when you use system components that might randomly fail (reading files from the OS when you dont have access, networking, etc).

Obviously you should always use third party libraries (or even your own code) correctly so the first of the above 3 "reasons" isnt a good reason at all. The other 2 reasons are unavoidable.

Examples:
B) You allow the user to customize your software with a plugin system. Users may write their own plugins, load them into the application and have them perform tasks. As the developer of your application it is impossible for you to know what exactly those plugins do and they might throw exceptions if they are nor properly written. For this reason you wrap all calls to the plugin system in try / catch blocks to make sure your application doesnt crash randomly because of faulty plugins.

C) You connect to a server to request certain data to be used by your application. The network might always randomly fail and a connection may be lost at any point in time. To make sure your application doesnt crash in these situations you wrap the networking code into try / catch blocks. When an exception is caught you display error dialogs to the user to let him know the connection was lost and he has to try again.


Edit:
By the way, even though it is possible you should NEVARR use exception to control the flow of your application. At least not in java. The performance of exceptions is horrendous compare to if/then/else statements. Every time an exception is generated the entire stack has to be traversed backwards to build the stacktrace. It also has to read all kinds of debug information from the .class files to generate a proper error message.


Try/catch blocks are super good for DB connections though. So that you can rollback in case of error.
Time is precious. Waste it wisely.
phar
Profile Joined August 2011
United States1080 Posts
September 25 2016 21:49 GMT
#15333
Yea, also quite necessary, e.g. towards the top of a service handler. Unless you like queries of death.
Who after all is today speaking about the destruction of the Armenians?
Deleted User 3420
Profile Blog Joined May 2003
24492 Posts
Last Edited: 2016-09-27 00:45:21
September 26 2016 23:29 GMT
#15334
It looks like me and my learning is propelling this thread forward. How nice of me to give you veterans something to do.

I am studying for my first exam for my OOP 2 class.

Here is some questions in the study guide I am not sure I understood (this isn't homework, I promise).

True or False?

"Interfaces are useful for inheritance"

I said true, but I thought the question is weird. I understand that a class doesn't actually extend the interface but it does in a way inherit it's properties, yes?


"interfaces are useful for polymorphism"

I didn't know what to say to this question. I believe polymorphism is just the concept that a subclass can be treated as either it's class type, or also as it's super classes. I didn't really know how to respond to this question.


"an interface can be used as a type"

I looked it up. It's true. I didn't know this. But I don't understand the example here:

http://docs.oracle.com/javase/tutorial/java/IandI/interfaceAsType.html

It seems they cast their object to the type relatable, which is their interface. Their interface requires that a class have the method isLargerThan(); . But in an interface, isLargerThan(); is empty, to be defined in the implementing class, right? So wtf does casting a random object to the interface type actually do? It doesn't have the isLargerThan(); method. So.. I don't get it.


"An interface can be used to create a 'polymorphic collection'"

-I have no idea. I've never heard of a polymorphic collection. I tried doing a google search. Not much information. I saw something about Collection<? extends A> . Don't know what this would have to do with interfaces.



edit: another question

why do constructors use the "this" keyword to set instance variables, but I keep seeing examples of copy constructors that *don't* use the "this" keyword when copying the variables?
icystorage
Profile Blog Joined November 2008
Jollibee19343 Posts
September 27 2016 00:42 GMT
#15335
I'm looking for other job opportunities, currently I'm employed on my first job starting entry level and currently a mid level dev. I have 3 years job exp. How's the market for AngularJS/.Net devs?
LiquidDota StaffAre you ready for a Miracle-? We are! The International 2017 Champions!
Birdie
Profile Blog Joined August 2007
New Zealand4438 Posts
September 27 2016 00:49 GMT
#15336
It seems they cast their object to the type relatable, which is their interface. Their interface requires that a class have the method isLargerThan(); . But in an interface, isLargerThan(); is empty, to be defined in the implementing class, right? So wtf does casting a random object to the interface type actually do? It doesn't have the isLargerThan(); method. So.. I don't get it.

Only classes which implement a particular interface can be cast to that interface. So it isn't a "random" object, it is an object which already implements all the methods in that interface.

It says that in that document: "If you define a reference variable whose type is an interface, any object you assign to it must be an instance of a class that implements the interface."

In the example given, the Object class must be implementing the Relatable interface (and therefore has a method implementation of isLargerThan).

Think of an interface as a contract which the implementing class agrees to follow. The "implement" keyword is the class signing the contract, and the interface's methods are the terms of the contract. The class must follow the contract by creating methods which are the same as the interface's methods. Any class which signs the interface contract can then have the interface's methods called on it, because it guarantees by signing it (with the "implement" keyword) that it will have a version of all the methods in an interface.
Red classic | A butterfly dreamed he was Zhuangzi | 4.5k, heading to 5k as support!
Blitzkrieg0
Profile Blog Joined August 2010
United States13132 Posts
Last Edited: 2016-09-27 01:22:35
September 27 2016 01:20 GMT
#15337
On September 27 2016 08:29 travis wrote:
edit: another question

why do constructors use the "this" keyword to set instance variables, but I keep seeing examples of copy constructors that *don't* use the "this" keyword when copying the variables?


public class Animal {

public String name;
public Object lazyExample;
public int id;

public Animal(String name, Object lazyExample, int id) {
this.name = name;
this.lazyExample = lazyExample;
this.id = id;
}

public Animal(Animal other) {
name = other.name;
lazyExample = new Object(other.lazyExample);
id = other.id;
}
}


You don't need the this keyword because the variables are not being shadowed. In the constructor the variable names are being shadowed by the parameters of the constructor method. However, I'd almost write it as follows because it improves readability which is more important.

public Animal(Animal other) {
this.name = other.name;
this.lazyExample = new Object(other.getLazyExample);
this.id = other.id;
}
I'll always be your shadow and veil your eyes from states of ain soph aur.
meatpudding
Profile Joined March 2011
Australia520 Posts
September 27 2016 02:03 GMT
#15338
On September 27 2016 08:29 travis wrote:
"An interface can be used to create a 'polymorphic collection'"

-I have no idea. I've never heard of a polymorphic collection. I tried doing a google search. Not much information. I saw something about Collection<? extends A> . Don't know what this would have to do with interfaces.


I'm not sure about this question either, the wording doesn't quite make sense. I think from your explanation that it's looking at container types, where you can define that the container takes a bunch of interface types, which could all be different actual types. Eg, if you had the interface Shape
list<Shape*> shapeList;
shapeList.append(new Circle);
shapeList.append(new Rectangle);
Be excellent to each other.
Deleted User 3420
Profile Blog Joined May 2003
24492 Posts
September 27 2016 02:26 GMT
#15339
On September 27 2016 09:49 Birdie wrote:
Show nested quote +
It seems they cast their object to the type relatable, which is their interface. Their interface requires that a class have the method isLargerThan(); . But in an interface, isLargerThan(); is empty, to be defined in the implementing class, right? So wtf does casting a random object to the interface type actually do? It doesn't have the isLargerThan(); method. So.. I don't get it.

Only classes which implement a particular interface can be cast to that interface. So it isn't a "random" object, it is an object which already implements all the methods in that interface.

It says that in that document: "If you define a reference variable whose type is an interface, any object you assign to it must be an instance of a class that implements the interface."

In the example given, the Object class must be implementing the Relatable interface (and therefore has a method implementation of isLargerThan).

Think of an interface as a contract which the implementing class agrees to follow. The "implement" keyword is the class signing the contract, and the interface's methods are the terms of the contract. The class must follow the contract by creating methods which are the same as the interface's methods. Any class which signs the interface contract can then have the interface's methods called on it, because it guarantees by signing it (with the "implement" keyword) that it will have a version of all the methods in an interface.


So then if the Object class is implementing the Relatable interface and therefore has a method implementation of isLargerThan , then what is the point of casting it to that interface type? It already has the method, so what new thing does casting it to the interface type do?
meatpudding
Profile Joined March 2011
Australia520 Posts
September 27 2016 02:46 GMT
#15340
On September 27 2016 11:26 travis wrote:
Show nested quote +
On September 27 2016 09:49 Birdie wrote:
It seems they cast their object to the type relatable, which is their interface. Their interface requires that a class have the method isLargerThan(); . But in an interface, isLargerThan(); is empty, to be defined in the implementing class, right? So wtf does casting a random object to the interface type actually do? It doesn't have the isLargerThan(); method. So.. I don't get it.

Only classes which implement a particular interface can be cast to that interface. So it isn't a "random" object, it is an object which already implements all the methods in that interface.

It says that in that document: "If you define a reference variable whose type is an interface, any object you assign to it must be an instance of a class that implements the interface."

In the example given, the Object class must be implementing the Relatable interface (and therefore has a method implementation of isLargerThan).

Think of an interface as a contract which the implementing class agrees to follow. The "implement" keyword is the class signing the contract, and the interface's methods are the terms of the contract. The class must follow the contract by creating methods which are the same as the interface's methods. Any class which signs the interface contract can then have the interface's methods called on it, because it guarantees by signing it (with the "implement" keyword) that it will have a version of all the methods in an interface.


So then if the Object class is implementing the Relatable interface and therefore has a method implementation of isLargerThan , then what is the point of casting it to that interface type? It already has the method, so what new thing does casting it to the interface type do?


You can still do stuff like
RelatableObject* relatable;
relatable = new Integer(3);
relatable->isLargerThan(PI);
relateble = new Real(3.5);
relateable->isLargerThan(PI);

Assuming that Integer and Real inherit the same interface. The point is that the isLargerThan method is never called on the concrete class, but only through the interface. (I know c++ doesn't have real interfaces, but whatever).
Be excellent to each other.
Prev 1 765 766 767 768 769 1031 Next
Please log in or register to reply.
Live Events Refresh
Next event in 2h 42m
[ Submit Event ]
Live Streams
Refresh
StarCraft: Brood War
GuemChi 1256
actioN 1009
Tasteless 243
Leta 234
PianO 232
Soma 123
Dewaltoss 71
Movie 36
Sacsri 32
EffOrt 31
[ Show more ]
Free 27
yabsab 26
Bale 18
Dota 2
ODPixel304
XcaliburYe257
League of Legends
JimRising 640
Counter-Strike
Stewie2K1778
shoxiejesuss22
Other Games
summit1g9494
SortOf117
Mew2King89
Liquid`RaSZi56
Organizations
Other Games
gamesdonequick12603
StarCraft 2
Blizzard YouTube
StarCraft: Brood War
BSLTrovo
sctven
[ Show 15 non-featured ]
StarCraft 2
• Berry_CruncH366
• AfreecaTV YouTube
• intothetv
• Kozan
• IndyKCrew
• LaughNgamezSOOP
• Migwel
• sooper7s
StarCraft: Brood War
• BSLYoutube
• STPLYoutube
• ZZZeroYoutube
Dota 2
• lizZardDota2114
League of Legends
• Rush1431
• Lourlo1188
• HappyZerGling136
Upcoming Events
Sparkling Tuna Cup
2h 42m
WardiTV European League
8h 42m
MaNa vs sebesdes
Mixu vs Fjant
ByuN vs HeRoMaRinE
ShoWTimE vs goblin
Gerald vs Babymarine
Krystianer vs YoungYakov
PiGosaur Monday
16h 42m
The PondCast
1d 2h
WardiTV European League
1d 4h
Jumy vs NightPhoenix
Percival vs Nicoract
ArT vs HiGhDrA
MaxPax vs Harstem
Scarlett vs Shameless
SKillous vs uThermal
uThermal 2v2 Circuit
1d 8h
Replay Cast
1d 16h
RSL Revival
2 days
ByuN vs SHIN
Clem vs Reynor
Replay Cast
2 days
RSL Revival
3 days
Classic vs Cure
[ Show More ]
FEL
3 days
RSL Revival
4 days
FEL
4 days
FEL
4 days
CSO Cup
4 days
BSL20 Non-Korean Champi…
4 days
Bonyth vs QiaoGege
Dewalt vs Fengzi
Hawk vs Zhanhun
Sziky vs Mihu
Mihu vs QiaoGege
Zhanhun vs Sziky
Fengzi vs Hawk
Sparkling Tuna Cup
5 days
RSL Revival
5 days
FEL
5 days
BSL20 Non-Korean Champi…
5 days
Bonyth vs Dewalt
QiaoGege vs Dewalt
Hawk vs Bonyth
Sziky vs Fengzi
Mihu vs Zhanhun
QiaoGege vs Zhanhun
Fengzi vs Mihu
Liquipedia Results

Completed

BSL Season 20
HSC XXVII
Heroes 10 EU

Ongoing

JPL Season 2
BSL 2v2 Season 3
Acropolis #3
KCM Race Survival 2025 Season 2
CSL 17: 2025 SUMMER
Copa Latinoamericana 4
Jiahua Invitational
Championship of Russia 2025
RSL Revival: Season 1
Murky Cup #2
BLAST.tv Austin Major 2025
ESL Impact League Season 7
IEM Dallas 2025
PGL Astana 2025
Asian Champions League '25
BLAST Rivals Spring 2025
MESA Nomadic Masters
CCT Season 2 Global Finals
IEM Melbourne 2025

Upcoming

2025 ACS Season 2: Qualifier
CSLPRO Last Chance 2025
CSL Xiamen Invitational
2025 ACS Season 2
CSLPRO Chat StarLAN 3
K-Championship
uThermal 2v2 Main Event
SEL Season 2 Championship
FEL Cracov 2025
Esports World Cup 2025
StarSeries Fall 2025
FISSURE Playground #2
BLAST Open Fall 2025
BLAST Open Fall Qual
Esports World Cup 2025
BLAST Bounty Fall 2025
BLAST Bounty Fall Qual
IEM Cologne 2025
FISSURE Playground #1
TLPD

1. ByuN
2. TY
3. Dark
4. Solar
5. Stats
6. Nerchio
7. sOs
8. soO
9. INnoVation
10. Elazer
1. Rain
2. Flash
3. EffOrt
4. Last
5. Bisu
6. Soulkey
7. Mini
8. Sharp
Sidebar Settings...

Advertising | Privacy Policy | Terms Of Use | Contact Us

Original banner artwork: Jim Warren
The contents of this webpage are copyright © 2025 TLnet. All Rights Reserved.