public class ProtectedClass {
private String name;
public static void changeName(ProtectedClass pc, String newName) {
pc.name = newName;
}
public ProtectedClass(String s) { name = s; }
public String toString() { return name; }
public static void main(String[] args) {
ProtectedClass
pc1 = new ProtectedClass("object1"),
pc2 = new ProtectedClass("object2");
pc2.changeName(pc1, "new string"); // expect ERROR/EXCEPTION
System.out.println(pc1);
}
} ///:~
Considering above Java source code,it could easily concluded that the Java programming language could only provide class-level access control/protect.Are there any programming languages providing object-level access control/protect?
thanks.
P.S:This problem is derived from this question Java: Why could base class method call a non-exist method?I want to give my appreciation to TofuBeer.
Scala has an object-private scope:
class A(){
private[this] val id = 1
def x(other : A) = other.id == id
}
<console>:6: error: value id is not a member of A
def x(other : A) = other.id == id
It compiles if you change the visibility to private:
class A(){
private val id = 1
def x(other : A) = other.id == id
}
Related
I am new to groovy and learning closures from this guide.
Whenever, in a closure, a property is accessed without explicitly setting a receiver object, then a delegation strategy is involved.
Shouldn't this return ALLAUDIN. Where am I doing wrong?
class Example {
class Person {
String name
Person(String name){
this.name = name
}
}
class Thing {
String name
Thing(String name){
this.name = name
}
}
static void main(String[] args){
Example e = new Example();
def p = new Person(e, 'allaudin')
def t = new Thing(e, 'laptop')
def getUpperName = { name.toUpperCase() }
getUpperName.delegate = p
println getUpperName() // EXAMPLE
}
}
You need to set the delegation strategy
Add the line:
getUpperName.resolveStrategy = Closure.DELEGATE_FIRST
Where you set the delegate
Hello this question is regarding when exactly New keyword i;e Method hiding in base class can be done.
static void Main(string[] args)
{
A a = new A();
a.calculatebnft();
a = new B();
a.calculatebnft();
a = new C();
a.calculatebnft();
a = new Program();
a.calculatebnft();
Console.ReadKey();
}
public new string calculatebnft()
{
string bnft = "";
Console.WriteLine("SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS");
return bnft;
}
}
class A
{
//my code here
public virtual string calculatebnft()
{
string bnft = "";
Console.WriteLine("A");//my code here
return bnft;
}
}
class B : A
{
//my code here
public override string calculatebnft()
{
string bnft = "";
Console.WriteLine("B");//my code here
return bnft;
}
}
class C : B
{
public new string calculatebnft()
{
string bnft = "";
Console.WriteLine("C");
return bnft;
}
}
When above program is executed output is
A
B
B
B
in this case New Keyword in class C not hiding method in class B? what is the reason behind it.
Sorry am new to .Net and if my question is too basic
Hi I have to different classes with Same properties and I want to access the peoperties of my classes Dynamically.
public Class1
{
public const prop1="Some";
}
public Class2
{
public const prop1="Some";
}
And in my code I am getting my class name like this
string classname="Session["myclass"].ToString();";//Say I have Class1 now.
And I want to get the prop1 value .
Something like
string mypropvalue=classname+".prop1";//my expected result is Some
///
Type typ=Type.GetType(classname);
Please help me in getting this
Reflection
var nameOfProperty = "prop1";
var propertyInfo = Class1Object.GetType().GetProperty(nameOfProperty);
var value = propertyInfo.GetValue(myObject, null);
for static:
var nameOfProperty = "prop1";
var propertyInfo = typeof(Class1).GetProperty("prop1", BindingFlags.Static);
var value = propertyInfo.GetValue(myObject, null);
Class reference from string
EDIT (I made example):
class Program
{
static void Main(string[] args)
{
var list = Assembly.Load("ConsoleApplication4").GetTypes().ToList();
Type ty = Type.GetType(list.FirstOrDefault(t => t.Name == "Foo").ToString());
//This works too: Type ty = Type.GetType("ConsoleApplication4.Foo");
var prop1
= ty.GetProperty("Temp", BindingFlags.Static | BindingFlags.Public);
Console.WriteLine(prop1.GetValue(ty.Name, null));
Console.ReadLine();
}
}
public static class Foo
{
private static string a = "hello world";
public static string Temp
{
get
{
return a;
}
}
}
Msdn
you can use following function to get a property value fron an object dynamically:
just pass object to scan & property name
public static object GetPropValue(object src, string propName)
{
return src.GetType().GetProperty(propName).GetValue(src, null);
}
I keep getting the exception “Unable to cast object of type X to Y” in some code. I’ve got an interface and two classes that implement it and it keeps throwing this error when casting from one to the other. The two classes and interface are in the same namespace in the same assembly so that’s not the issue. I created an isolated console application to figure this mess out but I can’t get them to cast to one another. I think I’ve forgotten some basic .Net rule here. Anything look off in this code to you?
My isolated app code:
class Program
{
static void Main(string[] args)
{
RecurringPaymentResult r = new RecurringPaymentResult();
r.AddError("test");
ProcessPaymentResult p = null;
p = (ProcessPaymentResult)r; // Doesn't compile. "Cannot convert type RecurringPaymentResult to ProcessPaymentResult"
p = (IPaymentResult)r; // Doesn't compile. "Cannot convert type RecurringPaymentResult to ProcessPaymentResult. An explicit conversion exists (are you missing a cast?)"
p = (ProcessPaymentResult)((IPaymentResult)r); // Compiles but throws: "Unable to cast object of type RecurringPaymentResult to ProcessPaymentResult" during runtime
}
}
My core code:
public interface IPaymentResult
{
IList<string> Errors { get; set; }
bool Success { get; }
void AddError(string error);
}
public partial class RecurringPaymentResult : IPaymentResult
{
public IList<string> Errors { get; set; }
public RecurringPaymentResult()
{
this.Errors = new List<string>();
}
public bool Success
{
get { return (this.Errors.Count == 0); }
}
public void AddError(string error)
{
this.Errors.Add(error);
}
}
public partial class ProcessPaymentResult : IPaymentResult
{
private PaymentStatus _newPaymentStatus = PaymentStatus.Pending;
public IList<string> Errors { get; set; }
public ProcessPaymentResult()
{
this.Errors = new List<string>();
}
public bool Success
{
get { return (this.Errors.Count == 0); }
}
public void AddError(string error)
{
this.Errors.Add(error);
}
// More properties and methods here…
}
One major mistake I see in your code is saying "p =".
You have already decided the type of p and you are assigning various other variables in this type which is wrong.
Below are all possible conversions available :
RecurringPaymentResult r = new RecurringPaymentResult();
r.AddError("test");
ProcessPaymentResult p = null;
var r1 = (IPaymentResult)r; //type of r1 becomes IPaymentResult
var r2 = (IPaymentResult)p; //type of r2 becomes IPaymentResult
var r3 = (RecurringPaymentResult)r1; //type of r3 becomes RecurringPaymentResult
var r4 = (ProcessPaymentResult)r2; //type of r4 becomes ProcessPaymentResult
Logical explaination:
Man (class) has Eye(interface) and Elephant(class) has Eye(interface). Interface provides See method(). Both Man and Deer implements Eye interface by having See method in them.
Now, What you are trying is converting Man object into Elephant object which is not possible as space to store those objects have different requirements.
I want to store many details (like name, email, country) of the particular person using the same key in hashtable or hashmap in java?
hashMap.put(1, "Programmer");
hashMap.put(2, "IDM");
hashMap.put(3,"Admin");
hashMap.put(4,"HR");
In the above example, the 1st argument is a key and 2nd argument is a value, how can i add more values to the same key?
You can achieve what you're talking about using a map in each location of your map, but it's a little messy.
Map<String, Map> people = new HashMap<String, Map>();
HashMap<String, String> person1 = new HashMap<String, String>();
person1.put("name", "Jones");
person1.put("email", "jones#jones.com");
//etc.
people.put("key", person1);
//...
people.get("key").get("name");
It sounds like what you might really want, though, is to define a Person class that has multiple properties:
class Person
{
private String name;
private String email;
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
//plus getters and setters for other properties
}
Map<String, Person> people = new HashMap<String, Person>();
person1 = new Person();
person1.setName("Jones");
people.put("key", person1);
//...
people.get("key").getName();
That's the best I can do without any information about why you're trying to store values in this way. Add more detail to your question if this is barking up the wrong tree.
I think what you are asking
let us assume you we want to store String page, int service in the key and an integer in the value.
Create a class PageService with the required variables and define your HashMap as
Hashmap hmap = .....
Inside pageService, what you need to do is override the equals() and hashcode() methods. Since when hashmap is comparing it checks for hashcode and equals.
Generating hashcode and equals is very easy in IDEs. For example in eclipse go to Source -> generate hashcode() and equals()
public class PageService {
private String page;
private int service;
public PageService(String page, int service) {
super();
this.page = page;
this.service = service;
}
public String getPage() {
return page;
}
public void setPage(String page) {
this.page = page;
}
public int getService() {
return service;
}
public void setService(int service) {
this.service = service;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((page == null) ? 0 : page.hashCode());
result = prime * result + service;
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
PageService other = (PageService) obj;
if (page == null) {
if (other.getPage() != null)
return false;
} else if (!page.equals(other.getPage()))
return false;
if (service != other.getService())
return false;
return true;
}
}
The following class is very generic. You can nest ad infinitum. Obviously you can add additional fields and change the types for the HashMap. Also note that the tabbing in the toString method should be smarter. The print out is flat.
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class HierarchicalMap
{
private String key;
private String descriptor;
private Map<String,HierarchicalMap>values=new HashMap<String,HierarchicalMap>();
public String getKey()
{
return key;
}
public void setKey(String key)
{
this.key = key;
}
public void addToSubMap(String key, HierarchicalMap subMap)
{
values.put(key, subMap);
}
public String getDescriptor()
{
return descriptor;
}
public void setDescriptor(String descriptor)
{
this.descriptor = descriptor;
}
public HierarchicalMap getFromSubMap(String key)
{
return values.get(key);
}
public Map<String,HierarchicalMap> getUnmodifiableSubMap()
{
return Collections.unmodifiableMap(values);
}
public String toString()
{
StringBuffer sb = new StringBuffer();
sb.append("HierarchicalMap: ");
sb.append(key);
sb.append(" | ");
sb.append(descriptor);
Iterator<String> itr=values.keySet().iterator();
while(itr.hasNext())
{
String key= itr.next();
HierarchicalMap subMap=this.getFromSubMap(key);
sb.append("\n\t");
sb.append(subMap.toString());
}
return sb.toString();
}