如何防止子类中的super方法(java)

时间:2017-03-27 05:53:09

标签: java inheritance subclass superclass

请注意这一点。 我有一个超级班

class A
{
    public void update(int num)
    {...}
}

并有另一个班级。继承A类

class B extends A
{
   public void update(string str)
   {...}
}

B obj = new B();
obj.update(50); // oh no, bad
obj.update(""); // yes

现在,我希望当我从B类创建新的时,A类的update()不能访问。 - 换句话说,我只想访问B的update()方法

3 个答案:

答案 0 :(得分:0)

只有在超类型和子类型中具有相同参数的相同方法名称有效地覆盖它时,才能阻止它。在你的情况下,signatues的方法是不同的..它们采用不同的参数,因此根据你作为参数传递的内容,它调用相应的方法。

答案 1 :(得分:0)

实际上你可以覆盖该方法并抛出异常是一种解决方案。

import UIKit
class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource, UITextFieldDelegate {

    @IBOutlet var deptLbl: UILabel!
    @IBOutlet var loginLbl: UILabel!
    @IBOutlet var real_nameLbl: UILabel!
    @IBOutlet var dropdownTxt: UITextField!
    @IBOutlet var dropdown: UIPickerView!

    var persons = [Person]()

    struct Person {
        var login: String
        var real_name: String

        init?(dict: [String:Any]) {
            guard let login = dict["login"] as? String, let real_name = dict["real_name"] as? String else {
                return nil
            }
            self.login = login
            self.real_name = real_name
        }
    }

    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return self.persons.count
    }
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return persons[row].real_name
    }
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        if row >= self.persons.count {
            return
        }
        self.loginLbl.text = self.persons[row].login
        self.real_nameLbl.text = self.persons[row].real_name
        self.dropdown.isHidden = true
        self.dropdownTxt.resignFirstResponder()
    }
    func textFieldDidBeginEditing(_ textField: UITextField) {
        if textField == self.dropdownTxt {
            self.dropdown.isHidden = false
        }
    }

    func getDropdownJSON(){
        deptLbl.text = "ITD"
        var request = URLRequest(url: URL(string: "http://localhost/getDeptList.php")!)
        request.httpMethod = "POST"
        let postString = "dept=\(deptLbl.text!)"
        request.httpBody = postString.data(using: .utf8)
        let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
            guard let data = data, error == nil else {
                print("error=\(error)")
                return
            }
            if let result = try? JSONSerialization.jsonObject(with: data, options: []) {
                print(result)
            }
        }
        task.resume()
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        getDropdownJSON()
    }
}

或者您可以使用泛型实现一个类。这可能不起作用但想法有效。

class A
{
    public void update(int num)
    {...}
}

class B extends A
{
   public void update(int i) { 
       throw new UnsupprotedOperationException();
   }
   public void update(string str)
   {...}
}

答案 2 :(得分:0)

将您的基类方法设为私有。

var offset = $('#slider1 img').offset();
	initDraw(document.querySelector('#slider1'));	
	function initDraw(canvas)
	{
		function setMousePosition(e) {
			var ev = e || window.event; //Moz || IE
			if (ev.pageX) { //Moz
				mouse.x = ev.pageX - offset.left;
				mouse.y = ev.pageY - offset.top;
				
			} else if (ev.clientX) { //IE
				mouse.x = ev.clientX + offset.scrollLeft;
				mouse.y = ev.clientY + offset.scrollTop;
			}

		};

		var mouse = {
			x: 0,
			y: 0,
			startX: 0,
			startY: 0
		};
		var element = null;

		canvas.onmousemove = function (e) {
			setMousePosition(e);
			if (element !== null) {
				element.style.width =Math.abs(mouse.x - mouse.startX) + 'px';
				element.style.height =Math.abs(mouse.y - mouse.startY) + 'px';
				element.style.left =(mouse.x - mouse.startX < 0) ? mouse.x + 'px' : mouse.startX + 'px';
				element.style.top =(mouse.y - mouse.startY < 0) ? mouse.y + 'px' : mouse.startY + 'px';
			}
		}

		canvas.onclick = function (e) {
			var i=0;
			if (element !== null) {
				element = null;
				canvas.style.cursor = "default";
				console.log("finsihed.");
			} else {
				var $rectangle = $('.rectangle');
				console.log("begun.");
				mouse.startX = mouse.x;
				mouse.startY = mouse.y;
				element = document.createElement('div');
				element.className ='rectangle para';				
				element.title =($rectangle.length + 1);				
				element.style.left =mouse.x +'px';
				element.style.top =mouse.y +'px';
				canvas.appendChild(element)
				canvas.style.cursor ="crosshair";
				
				/*$('.rectangle').clayfy(
				{
					type : 'resizable',
					minSize :[15,15],
					maxSize :[2600,2300],
				});*/					
			}
			
		}
	}